注销时ExpressionChangedAfterItHasBeenCheckedError

时间:2017-09-09 04:27:55

标签: angular

我的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黑客,这些都不可取......这里还有其他选择吗?

1 个答案:

答案 0 :(得分:0)

在AppComponent中,您必须在更改后显式运行检测:

constructor(pivate _changeDetectorRef: ChangeDetectorRef) { }
    ngAfterViewChecked(): void {
        this._changeDetectorRef.detectChanges();
}

记住要从角铁芯导入它:

import { Component, ChangeDetectorRef, AfterViewChecked } from '@angular/core';