我正在尝试从Angular 6应用程序的导航栏菜单中隐藏登录项。我有一个AuthService
,如下所示:
import { Injectable, Inject } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private url: string;
private loggedIn = new BehaviorSubject<boolean>(false);
isLoggedIn$ = this.loggedIn.asObservable();
constructor(private http: HttpClient, private jwtHelper: JwtHelperService, @Inject('BASE_URL') baseUrl: string) {
this.url = baseUrl + 'api/auth';
this.loggedIn.next(this.isLoggedIn());
}
login(credentials) {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post<any>(`${this.url}/login`, JSON.stringify(credentials), { headers: headers }).pipe(
map(response => {
if (response && response.token) {
localStorage.setItem('token', response.token);
this.loggedIn.next(true);
return true;
}
return false;
})
);
}
logout() {
localStorage.removeItem('token');
this.loggedIn.next(false);
}
isLoggedIn() {
return !this.jwtHelper.isTokenExpired();
}
}
这就是我的NavMenuComponent
中的东西:
export class NavMenuComponent implements OnInit, OnDestroy {
isExpanded = false;
isLoggedIn: boolean;
authSubscription: Subscription;
constructor(private router: Router, private authService: AuthService) {}
ngOnInit() {
this.authSubscription = this.authService.isLoggedIn$
.subscribe(loggedIn => this.isLoggedIn = loggedIn);
}
ngOnDestroy() {
this.authSubscription.unsubscribe();
}
onLogout() {
this.authService.logout();
this.router.navigate(['/login']);
}
collapse() {
this.isExpanded = false;
}
toggle() {
this.isExpanded = !this.isExpanded;
}
}
而且,这是html:
<li *ngIf="!isLoggedIn" class="nav-item" [routerLinkActive]="['link-active']">
<a class="nav-link" [routerLink]="['/login']">Login</a>
</li>
但是,当我运行它时,出现以下错误:
错误:ExpressionChangedAfterItHasBeenCheckedError:表达式具有 检查后更改。先前的值:'ngIf:true'。当前 值:“ ngIf:false”。
我确实读过有关此错误的信息,但是我不明白如何解决该错误。有帮助吗?
答案 0 :(得分:0)
我的猜测是,这与您在服务构造函数中为loggedIn
设置初始值的方式有关:this.loggedIn.next(this.isLoggedIn());
尝试仅在您的类中声明变量,并仅在构造函数中将其设为new BehaviourSubject()
。
类似的东西:
private url: string;
private loggedIn: BehaviorSubject<boolean>;
isLoggedIn$: Observable<boolean>;
constructor(private http: HttpClient, private jwtHelper: JwtHelperService, @Inject('BASE_URL') baseUrl: string) {
this.url = baseUrl + 'api/auth';
this.loggedIn = new BehaviourSubject<boolean>(this.isLoggedIn());
this.isLoggedIn$ = this.loggedIn.asObservable()
}
让我知道这是否有任何改变
答案 1 :(得分:0)
您尝试使用方法而不是属性来返回AuthService上的可观察对象
isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject(false);
isLoggedIn$() {
return this.isLoggedIn.asObservable();
}
答案 2 :(得分:0)
您可以使用setTimeout解决此错误。
export class NavMenuComponent implements OnInit, OnDestroy {
isExpanded = false;
isLoggedIn: boolean;
authSubscription: Subscription;
constructor(private router: Router, private authService: AuthService) {}
ngOnInit() {
setTimeout(() => {
this.authSubscription = this.authService.isLoggedIn$
.subscribe(loggedIn => this.isLoggedIn = loggedIn);
});
}
ngOnDestroy() {
this.authSubscription.unsubscribe();
}
onLogout() {
this.authService.logout();
this.router.navigate(['/login']);
}
collapse() {
this.isExpanded = false;
}
toggle() {
this.isExpanded = !this.isExpanded;
}
}