2016-07-07 54 views
2

我想重定向到我的家庭组件认证后。重定向成功,但主页组件不呈现。如果我将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浏览器开发工具,我可以看到所有的家庭成分的模板除了一个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

什么是'authService'authenticationStream'? –

+0

'authService.authenticationStream()'返回一个表示验证状态的布尔值的Observable流 –

+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'])); 
      } 
     }); 
    } 
} 
+0

我认为可能值得研究为什么会发生这种情况,可能更适合使用'zone.run() '代码开始在区域外运行,但为此我需要看到更多的代码('authService.authenticationStream'和使用它发出事件的地方)。 –

+0

Hey Gunter,zone.run做什么?创建一个新的范围? – inoabrian

+3

Angular2在区域内运行代码。区域是一个范围,其中(大多数)异步API('addEventHandler','removeEventHandler','setTimeout',...)被修补,以便在发生某些事件时通知Angular2。每当发生事件并且所有事件处理程序完成时,Angular2都会运行更改检测。如果代码在Angulars区域之外运行,则不会发生更改检测,这会导致您描述的行为。 'zone.run()'使一个执行线程(可能在Angulars区域之外)在其区域内继续。 在使用某些未打补丁的异步API时,运行Angulars区域外的代码。 –

相关问题