2016-11-30 3 views
2

私のアプリケーションのfirebase認証を作成しようとしています。ここで私のアプリケーションコンポーネントのauth.serviceからisLoggedIn boolan値を取得する方法

は、私が何をしたいのかauth.service.ts

private isloggedIn = false; 
    constructor(private af: AngularFire, private router: Router) { 
    // this.af.auth.subscribe((auth) => console.log(auth)); 
    this.af.auth.subscribe(user => { 
    if (user) { 
     this.isloggedIn = 'true'; 
    } else { 
     this.isloggedIn = 'false'; 
    } 
    }); 


    } 


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { 
    return this.af.auth.map((auth) => { 
     if(auth == null) { 
     this.router.navigate(['/auth']); 
     return false; 
     } else { 
     return true; 
     } 
    }).first() 
    } 

isLoggedIn() { 
return this.isloggedIn; 
} 

である認証状態のために観察することです。それが変更されると、this.isloggedInも変更されます。

次に、コンポーネントでisloggedin auth.serviceの値を取得します。

瞬間
import { AuthService } from './auth.service'; 
export class SomeComponent implements OnInit { 



     constructor(private titleService: Title, private AuthService : AuthService, public toastr: ToastsManager, private af: AngularFire) { 

     } 

    ngOnInit() { 
     this.titleService.setTitle("some component title"); 
      console.log(this.AuthService.isLoggedIn()); 
     } 

、私はthis.AuthService.isLoggedInを(使用)ユーザがログインした後であっても、未定義の私に与えます。私が間違っているのか?

答えて

0

これは、サーバーからの応答が利用可能になる前にisLoggedIn()が呼び出されたためです。非同期コールが適切に連鎖されていることを確認する必要があります。そうしないと、前のコールがすでに完了していることを確認できません。

private isloggedIn:Subject = new BehaviorSubject(false); 
    constructor(private af: AngularFire, private router: Router) { 
    this.isLoggedIn = this.af.auth.map(user => { // map instead of subscribe 
    if (user) { 
     this.isloggedIn = 'true'; 
    } else { 
     this.isloggedIn = 'false'; 
    } 
    }); 
    } 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { 
    return this.isLoggedIn.map((auth) => { 
     if(auth == null) { 
     this.router.navigate(['/auth']); 
     return false; 
     } else { 
     return true; 
     } 
    }).first() 
    } 
ngOnInit() { 
    this.titleService.setTitle("some component title"); 
     console.log(this.AuthService.isLoggedIn.subscribe(value => console.log(value)); 
    } 

も参照してくださいWhat is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

関連する問題