2016-11-30 48 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?

相關問題