Angular 6 AuthGuard [英] Angular 6 AuthGuard

查看:123
本文介绍了Angular 6 AuthGuard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未通过身份验证,我只是想隐藏菜单.拜托,别担心令牌,我还没做完.

I'm just trying to hide menu if the user is not authenticated. Please, Don't worry about the token, I have not done yet.

出什么问题了?如果 isLoggedIn 为true,则!isLoggedIn 应该为false,但不能那样做!

What is the problem? if isLoggedIn is true, !isLoggedIn should be false, but it doesn't works like that!!

在AppComponentHTML中:

In AppComponentHTML:

<app-menu *ngIf="isLoggedIn | async"></app-menu>
<router-outlet *ngIf="!isLoggedIn | async"></router-outlet>

如果用户通过身份验证,

应用程序菜单可以正常工作,但路由器出口则不能.

app-menu works fine if user is authenticated, but router-outlet doesn't.

这是我下面的代码的其余部分:

Here is the rest of my code below:

AuthGuard:

AuthGuard:

import {Injectable} from '@angular/core';
import {CanActivate, CanLoad, Router} from '@angular/router';
import {BehaviorSubject, Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuardService implements CanActivate, CanLoad {

  constructor(private router: Router) {}

  loggedIn = new BehaviorSubject<boolean>(false);
  localStorage;

  isLoggedIn(): Observable<boolean> {
    return this.loggedIn.asObservable();
  }

  authenticationHandler(): boolean {
    this.localStorage = localStorage.getItem('token');
    if (this.localStorage) {
      this.loggedIn.next(true);
      return true;
    } else {
      this.loggedIn.next(false);
      this.router.navigate(['/login']);
      return false;
    }
  }

  canActivate(): boolean {
    return this.authenticationHandler();
  }

  canLoad(): boolean {
    return this.authenticationHandler();
  }
}

AppComponentTS:

AppComponentTS:

import {Component, OnInit} from '@angular/core';
import {AuthGuardService} from './services/auth-guard.service';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  isLoggedIn: Observable<boolean>;

  constructor(private authGuardService: AuthGuardService) {}

  ngOnInit() {
    this.isLoggedIn = this.authGuardService.isLoggedIn();
    console.log(this.isLoggedIn);
  }

}

推荐答案

我认为您需要

<router-outlet *ngIf="!(isLoggedIn | async)"></router-outlet>

这篇关于Angular 6 AuthGuard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆