2017-01-04 31 views
1

ユーザのログイン状態に応じて、Angular2アプリでヘッダを表示/非表示しようとしています。ヘッダーは、ユーザーがログインしている場合にのみ表示されます。ログインの場合は、parse(parse.com)を使用しています。すべて正常に動作していますが、ヘッダーを表示するかどうかを示す変数がビュー内で更新されていません。コンポーネントクラスでは、ログイン後に変数がtrueに設定されていますが、テンプレートは更新されません。 フローは次のとおりです。 - ユーザーがログインページに行くと何のヘッダがあり てはならない - ユーザーlogges 中 - ユーザーがダッシュボードにリダイレクトされ、ヘッダは私が持っている私のテンプレートで角度2 - ビューで変数が更新されない

import { Component } from '@angular/core'; 
import { ParseProviderService } from "../../shared/providers/parse-provider.service"; 
import { Router } from "@angular/router"; 

@Component({ 
    selector : 'app-header', 
    templateUrl : './header.component.html', 
    styleUrls : [ './header.component.css' ] 
}) 
export class HeaderComponent { 

    public showHeader: boolean; 

    constructor(private parseProviderService: ParseProviderService, 
       private router: Router) { 
     this.showHeader = !!this.parseProviderService.current(); 
     console.log("Header: ", this.showHeader); // Shows the login state 
     this.parseProviderService.getCurrentSubject().subscribe((show) => { 
      console.log(show); // show == true after login 
      this.showHeader = show; // Also if show == true the template will not update 
     }); 
    } 

    logout() { 
     this.parseProviderService.logout().then(() => { 
      this.parseProviderService.getCurrentSubject().next(false); 
      this.router.navigate(['/user/login']); 
     }, (error) => { 
      console.log(error); 
     }); 
    } 

} 

表示されるはずです私は数日以来、それを見つけることができませんでした

Show Header: {{ showHeader }} 

:(

答えて

1

あなたは:このような何かdetectChanges()などを使用して手動で変更検出を呼び出す必要があります。

constructor(private parseProviderService: ParseProviderService, 
      private router: Router, private cdRef:ChangeDetectorRef) { 
    this.showHeader = !!this.parseProviderService.current(); 
    console.log("Header: ", this.showHeader); // Shows the login state 
    this.parseProviderService.getCurrentSubject().subscribe((show) => { 
     console.log(show); // show == true after login 
     this.showHeader = show; // Also if show == true the template will not update 
     cdRef.detectChanges(); // <<<<< added 
    }); 
} 
+0

ありがとう、Günter!魅力のように動作します。あなたは私が自分でそれを実装する必要がある理由を知っていますか? – Ikno0wit

+1

'parseProviderService'のように見えますが、どういうわけかAngularsゾーンが残っています。 Angularは、非同期コールバックを認識し、その後の変更検出を実行します。何とかparseがzone.jsと完全に互換性がないようです –

関連する問題