如果用户未通过身份验证,我只是想隐藏菜单。 拜托,别担心令牌,我还没有做。
出什么问题了? 如果 isLoggedIn 为true,则!isLoggedIn 应该为false,但不能那样做!
在AppComponentHTML中:
<app-menu *ngIf="isLoggedIn | async"></app-menu>
<router-outlet *ngIf="!isLoggedIn | async"></router-outlet>
如果用户通过身份验证,应用程序菜单可以正常工作,但路由器出口则无法。
下面是我的其余代码:
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:
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);
}
}
答案 0 :(得分:1)
我认为您需要
<router-outlet *ngIf="!(isLoggedIn | async)"></router-outlet>