Angular 验证未呈现组件后路由器导航重定向
我想在身份验证后重定向到我的主组件。重定向成功,但主组件未渲染。如果我将this.router.navigate移到订阅块之外,它将正确渲染Angular 验证未呈现组件后路由器导航重定向,angular,angular2-routing,Angular,Angular2 Routing,我想在身份验证后重定向到我的主组件。重定向成功,但主组件未渲染。如果我将this.router.navigate移到订阅块之外,它将正确渲染 export class LoginComponent implements AfterViewInit { constructor(private router: Router, private authService: AuthenticationService) { this.authServ
export class LoginComponent implements AfterViewInit {
constructor(private router: Router,
private authService: AuthenticationService) {
this.authService.authenticationStream().subscribe(isAuthenticated => {
if (isAuthenticated) {
this.router.navigate(['/home']);
}
});
}
}
在chrome开发工具中,我可以看到除ngFor块之外的所有主组件模板:
<md-grid-tile *ngFor="let tile of CONFIG.tiles">
{{ tile }}
</md-grid-tile>
{{tile}}
我可以验证是否填充了CONFIG.tiles
为什么在导航之后不呈现ngFor块,特别是从可观察订阅中的导航调用
编辑:添加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);
}
}
导出类身份验证服务{
构造函数(私有http:HttpService,
私人店铺(零售店){
}
authenticate():void{
让我来看看http://uri.com'
this.http.post(uri).subscribe(()=>{
//如果用户成功通过身份验证,则向ngrx存储发送事件
this.store.dispatch({type:AUTHENTICATED});
});
}
authenticationStream():可观察{
//从分派调用发出事件
返回此.store.select(身份验证);
}
}
听起来像是authenticationStream
在Angulars区域之外发出事件,这会破坏更改检测并导致您描述的行为
您可以使用zone.run()
强制执行回到角度区域:
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']));
}
});
}
}
什么是
authService
authenticationStream`?authService.authenticationStream()
返回一个可观察的布尔值流,指示身份验证状态。请添加显示身份验证状态的代码。我认为可能值得研究为什么会发生这种情况,最好应用zone.run()
代码开始在区域外运行,但为此,我需要查看更多代码(authService.authenticationStream
以及使用它发出事件的位置)。嘿,冈特,zone.run做什么?创建新范围?Angular2在区域内运行代码。区域是(大多数)异步API(addEventHandler
,removeEventHandler
,setTimeout
,…)被修补的范围,以便Angular2在发生某些事件时得到通知。Angular2在每次事件发生和所有事件处理程序完成时运行更改检测。如果代码在Angulars区域之外运行,则不会发生更改检测,这将导致您描述的行为zone.run()
使执行线程(可能在Angulars区域之外)在其区域内继续。当使用一些未修补的异步API时,会发生在Angulars区域外运行的代码。我不知道store
或是什么原因导致它在Angulars区域外运行。即使看到更多的代码,我也没有比上面的答案更好的解决方案。我遇到了类似的问题,试图在NgZone中包装调用,但看到您如何仅在zone.run中包装订阅回调,就成功了。万分感谢!