我想在身份验证后重定向到我的主组件。重定向成功,但主组件不呈现。如果我在订阅块之外移动this.router.navigate,它将正确呈现。
export class LoginComponent implements AfterViewInit {
constructor(private router: Router,
private authService: AuthenticationService) {
this.authService.authenticationStream().subscribe(isAuthenticated => {
if (isAuthenticated) {
this.router.navigate(['/home']);
}
});
}
}
在chrome dev工具中,除了ngFor块之外,我可以看到所有主页组件的模板:
<md-grid-tile *ngFor="let tile of CONFIG.tiles">
{{ tile }}
</md-grid-tile>
我可以验证CONFIG.tiles是否已填充。
为什么导航后不会渲染ngFor块,特别是来自Observable订阅内的导航调用?
编辑:添加AuthenticationService代码:
export class AuthenticationService {
constructor(private http: HttpService,
private store: Store<AppStore>) {
}
authenticate(): void {
let uri = 'http://uri.com'
this.http.post(uri).subscribe(() => {
// Dispatch event to ngrx store if user is successfully authenticated
this.store.dispatch({type: AUTHENTICATED});
});
}
authenticationStream(): Observable<boolean> {
// Emits events from dispatch calls
return <Observable<boolean>> this.store.select(AUTHENTICATION);
}
}
答案 0 :(得分:3)
听起来authenticationStream
会在Angulars区域外发出事件,这会破坏变更检测并导致您所描述的行为。
您可以使用zone.run()
强制执行返回Angulars区域:
export class LoginComponent implements AfterViewInit {
constructor(private router: Router,
private authService: AuthenticationService
zone: NgZone) {
this.authService.authenticationStream().subscribe(isAuthenticated => {
if (isAuthenticated) {
zone.run(() => this.router.navigate(['/home']));
}
});
}
}