2017-10-11 31 views
0

我正在使用Firebase進行Google身份驗證。但問題是當我連接並刷新頁面時,我想獲取Session/CurrentUser。 在文檔我必須使用:Angular 4 - Firebase - 檢查用戶是否已連接

firebase.auth().onAuthStateChanged(function(user) { 
    if (user) { 
    console.log(user) 
    // User is signed in. 
    } else { 
    // No user is signed in. 
    } 
}); 

此功能,但問題是我不知道TU如何使用可觀察等待這個函數的結尾。因爲這個函數類似於ajax函數,並且角度不會等待,所以如果我將用戶設置爲局部變量,它將爲空。

我已經搜查計算器,我沒有找到一個解決方案

謝謝

+0

您可以使用firebase.auth()。currentUser查看它是否已經連接到初學者。如果你想使用onAuthStateChanged,你想在事後發生什麼?你不能把其餘的if(用戶)塊? – Carsten

+2

看看angularfire2 –

回答

2

這我的回答與@wandrille的解決方案相結合:

您可以使用Subject代替Observable這樣:

import { Subject } from "rxjs/Subject"; 

class AuthService{ 
    public connectionSubject : Subject<string>() = new Subject<string>(); 

    firebase.auth().onAuthStateChanged(function(user) { 
    if (user) { 
     console.log(user) 
     this.connectionSubject.next({ state : "connected", user}); 
    } else { 
     this.connectionSubject.next("disconnected"); 
    } 
    }); 


} 
在組件

@Component({ 
    //... 
    }) 
    class YourComponent{ 
     constructor(private authService: AuthService){ 
     } 
     ngOnInit(){ 
     this.authService.connectionSubject.subscribe((data) => { 
      if(data.state === 'connected'){ 
       console.log(data.user); 
      }else{ 
       //... 
      } 
     }); 
     } 
    } 
+0

在你的例子中,變量用戶將會使用戶滿意。但是我怎麼能在我的控制器中返回這個用戶?我想控制用戶是否連接,如果不是,我想限制他一些路線 – Fasco

+0

@Fasco查看更新 –

2

我建議你使用angularFire2:

您可以爲您的驗證SYSTEME的服務。

一些例子:

@Injectable() 
export class AuthService { 

    public firebaseUser : Observable <firebase.User>; 
    public currentUser : firebase.User; 

    constructor(public afAuth : AngularFireAuth) { 

    this.firebaseUser = this.afAuth.authState 

    } 

    isAuthentificated() { 
    return this.firebaseUser 
    } 

    getCurrentUSer() { 
    return this.afAuth.auth.currentUser 
    } 

    loginUser({email, password}){...some code...} 
} 

而且你剛纔打電話getCurrentUSer()isAuthentificated()在你的組件。

+0

我使用angularFire2。你的方法正在工作,但問題是我想檢查currentUser是否不在控制器中。但是,如果我在控制器中執行此操作,則curent用戶始終爲空 – Fasco