2016-07-07 8 views
2

認証後に私のホームコンポーネントにリダイレクトしたい。リダイレクトは成功しましたが、ホームコンポーネントはレンダリングされません。 subscribeブロックの外で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']); 
      } 
     }); 
    } 
} 

は、クロームのdevのツールでは、私はngForブロック以外のホームコンポーネントのテンプレートのすべてを見ることができます:

<md-grid-tile *ngFor="let tile of CONFIG.tiles"> 
    {{ tile }} 
</md-grid-tile> 

私が移入されCONFIG.tilesを確認することができます。

なぜngForブロックは、Observableサブスクリプション内のナビゲートコールからナビゲートしてレンダリングされないのですか?

EDIT: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ゾーン外のイベントを発するように聞こえます。

あなたが戻って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'])); 
      } 
     }); 
    } 
} 
+0

なぜそれが起こるのか調べる価値があるかもしれないと思うかもしれません。 'コードがゾーンの外側で実行され始めるが、それ以上のコード(' authService.authenticationStream'とそれを使ってイベントが発行される場所)を見る必要がある。 –

+0

Hey Gunter、zone.runは何をしますか?新しいスコープを作成しますか? – inoabrian

+3

Angular2はゾーン内でコードを実行します。ゾーンは、(ほとんどの)非同期API( 'addEventHandler'、' removeEventHandler'、 'setTimeout'、...)がパッチされて、何らかのイベントが発生したときにAngular2に通知されるスコープです。 Angular2は、イベントが発生し、すべてのイベントハンドラが完了するたびに変更検出を実行します。 Angularsゾーン外でコードが実行されると、変更の検出が行われず、これが記述した動作につながります。 'zone.run()'は実行中のスレッド(Angularsゾーン外にあるかもしれません)をそのゾーン内で続けさせます。 パッチの適用されていない非同期APIが使用されると、Angularsゾーン外で実行されるコードが発生します。 –

関連する問題