2017-10-17 31 views
0

我有很多方法需要currentUserId。 我已經注入我的AuthService獲取和存儲用戶像這樣:如何獲得當前認證的用戶angularfire2(角度),以便它可以在類方法中及時使用?

// AuthService代碼

getAuthorizationState() { 
    return this.afAuth.authState; 
} 

//訂閱組件代碼

constructor(...auth: AuthService...) { 
    this.user = this.auth.getAthorizationState(); 
    this.user.subscribe(
     (value) => { 
      console.log('value', value); 
      this.currentUser = value; 
     } 
    ); 
} 

// This tends to throw an error can not get property uid of undefined 
getUserFeed(uri: string): Obervable<any> { 
    return this.getFeed(`feed/${this.currentUser.uid})`) 
} 

// So have been resorting to this 
getUserFeed(uri: string): Obervable<any> { 
    this.user.map((user) => {return user.uid}) 
     .flatMap((currentUserId) => { 
      return this.getFeed(`feed/${currentUserId})`) 
     }); 

    } 

問題:一直有到用everymethod做到這一點。在angularjs中,我記得我相信使用解析方法來解決這個問題。

問題:是一個有一個「應用程序的全球」的方式來獲取和存儲當前認證用戶的信息,以便它已經有調用組件或注射服務的方法是什麼時候?

回答

0

在角度上,我被告知我正在做的可觀察鏈確實是使用的模式。我稍微修改了它,並將重構使用它在服務與組件。

getHomeFeedPostsWrapper(): Observable<any> { 
    return getUserId().map((user) => { 
     return user.uid; 
    }).switchMap((userId) => { 
     return this.friendly.getHomeFeedPosts(userId); 
    }); 
} 


/** 
* Helper methods 
*/ 

getUserId() { 
    return this.auth.getAuthState().map((user) => { 
     return user.uid; 
    }); 
} 
相關問題