[英]ExpressionChangedAfterItHasBeenCheckedError when logging out
我的app.component.html
有幾個這樣的鏈接:
<a *ngIf="!global.isLoggedIn()" routerLink="/account" routerLinkActive="active">Login</a>
<a *ngIf="global.isLoggedIn()" routerLink="/account-logout" routerLinkActive="active">Logout</a>
在app.component.ts
我有這個:
constructor(private global: GlobalService, private route: ActivatedRoute) { }
在我的global.service.ts
我有:
public isLoggedIn(): boolean {
return this.authService.isLoggedIn();
}
在我的authhttp.service.ts
我有:
public logout() {
sessionStorage.removeItem(this.tokeyKey);
}
public isLoggedIn(): boolean {
let token = sessionStorage.getItem(this.tokeyKey);
return token != null;
}
在我的account.component.ts
我有:
constructor(private router: Router, private authService: AuthHttpService, private global: GlobalService, private route: ActivatedRoute) { }
ngOnInit() {
this.subscriptions.push(this.route.data.subscribe(data => {
this.global.setMetaTitle(data.title);
this.handleLogout(data.logout == true);
}));
}
private handleLogout(isLogout: boolean) {
if (isLogout) {
this.authService.logout();
this.router.navigate([""]);
}
}
不確定它會有所幫助,但這是route
:
{ path: 'account-logout', component: AccountComponent, data: { title: 'Logout - My App', logout: true } },
根據我讀過的所有內容,這是因為我正在ngOnInit
進行注銷交易,但我不確定如何處理它,除了創建一個LogoutComponent
或更糟糕的是使用setTimeout
hack,這些都不是是可取的……這里還有其他選擇嗎?
在 AppComponent 中,您必須在更改后顯式運行檢測:
constructor(pivate _changeDetectorRef: ChangeDetectorRef) { }
ngAfterViewChecked(): void {
this._changeDetectorRef.detectChanges();
}
記得從 angular core 導入它:
import { Component, ChangeDetectorRef, AfterViewChecked } from '@angular/core';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.