[英]Angular does not execute bindings, directive and ngOnInit when route change
在我的應用程序中,我遇到了Angular不綁定屬性的問題。 它還不會調用ngOnInit
和ngAfterViewInit
或execute指令。
這是部分LoginComponent代碼:
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit
//.....
public test: string = 'some dummy test';
constructor(
private cd: ChangeDetectorRef,
private fb: FormBuilder, private router: Router, private route: ActivatedRoute,
private authService: AuthService,
private usersService: UserService,
private notificationsService: NotificationsService
)
{
this.loginForm = fb.group({
email: ["", Validators.required],
password: ["", Validators.required]
});
console.info("constructor");
}
ngOnInit()
{
console.info("ngOnInit");
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
ngAfterViewInit()
{
this.initGapi();
console.info("afterviewinit");
}
奇怪的是,這在我打開頁面或HMR刷新頁面時有效,但在我登錄和注銷時卻無效。
這是注銷代碼:
logout(): boolean
{
this.authService.logout();
}
//authservice.ts
logout()
{
localStorage.removeItem("token");
localStorage.removeItem("refresh_token");
localStorage.removeItem("profile");
if (gapi.auth2)
{
const instance = gapi.auth2.getAuthInstance();
if (instance)
{
instance.signOut().then(() =>
{
this.router.navigate(["login"]);
});
return;
}
}
this.router.navigate(["login"]);
}
我注銷和綁定不發生時的區別是:
按鈕沒有樣式。 這應該做kendoButton
指令<button class="center" kendoButton type="submit">
缺少與測試的綁定(一些虛擬測試)
ngOnInit
和ngAfterViewInit
。 控制台中沒有錯誤。 我還記錄屏幕(從空白頁開始)。 我擁有最新的Chrome和Firefox,並且兩個瀏覽器都存在相同的問題。
是否有人知道哪里出了問題或我還能嘗試什么?
如果gapi
運行Angulars區外,然后更改檢測沒有得到通知運行。 您可以在Angulars區域內顯式運行代碼,例如
constructor(private zone:NgZone) {}
...
this.zone.run(() => {
this.router.navigate(["login"])
});
問題出在Google gapi庫中:
const instance = gapi.auth2.getAuthInstance();
if (instance)
{
instance.signOut().then(() =>
{
this.router.navigate(["login"]); //This is runned outside Angular's context.
});
return;
}
回調instance.signOut
在Angular的上下文之外運行。 解決方案是將導航放置在google.gapi
回調之外:
const instance = gapi.auth2.getAuthInstance();
if (instance)
{
instance.signOut();
this.router.navigate(["login"]);
}
或者,如果您希望從Google注銷后導航,請使用區域。 這可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.