2017-06-29 47 views
0

我有一個使用Angular 4,ngrx和AngularFire2構建的項目。我正在嘗試檢索當前登錄用戶的uid並將其放入我的商店。AngularFire2 return可觀察到ngrx效果

任何想法或援助,將不勝感激。

錯誤

ERROR TypeError: Cannot read property 'map' of undefined 
    at SwitchMapSubscriber.project (auth.effects.ts:22) 

影響代碼

@Effect() getAccountId$ = this.actions$ 
      .ofType(ActionTypes.GET_ACCOUNT_ID) 
      .map(action => 
// This is line 22 where the error is coming 
       this.authService.getCurrentUserId() 
        .map(authObject => ({ type: ActionTypes.GET_ACCOUNT_ID_SUCCESS, payload: authObject })) 
        .catch(() => Observable.of({ type: ActionTypes.GET_ACCOUNT_ID_ERROR }))); 

服務代碼

用戶名:任何; //聲明爲任何。如果我嘗試使其成爲Observable,那麼我會在this.userId = user.uid上得到一個編譯錯誤;在調用afAuth說,它不能指定字符串可觀察

userId: any; 

    getCurrentUserId(): Observable<any> { 

     this.afAuth.authState.subscribe(
      (user: firebase.User) => { 
      if (user != null) { 
       this.userId = user.uid; 
       console.log('constructor auth object: ', user); 
       console.log('constructor userId: ', this.userId); 
      } 
      }); 

     return this.userId; 
     } 
+0

如果在'.ofType(ActionTypes.GET_ACCOUNT_ID)'行之前和之後執行'.do(res => console.log(res)),你會得到什麼? – crash

+0

我不認爲你的'this.userId'是一個'Observable'。 –

+0

嗨感謝您的快速回復。我不能把它放在那行前,因爲我得到一個編譯錯誤,但在我得到對象{類型:「GET_ACCOUNT_ID」,有效載荷:「」}。我已經確定了問題所在,只是不確定如何解決問題。基本上,對auth對象的調用是一個subsciption,所以它在訂閱完成之前返回this.userId效果,所以它返回undefined – ccocker

回答

0

感謝你們的幫助,最終的溶液如下: -

影響代碼

@Effect() getAccountId$ = this.actions$ 
     .ofType(ActionTypes.GET_ACCOUNT_ID) 
     .switchMap(action => 
      this.authService.getCurrentUserId() 
       .map(authObject => ({ type: ActionTypes.GET_ACCOUNT_ID_SUCCESS, payload: authObject })) 
       .catch(() => Observable.of({ type: ActionTypes.GET_ACCOUNT_ID_ERROR }))); 

服務代碼

getCurrentUserId(): Observable<firebase.User> { 

return this.afAuth.authState; 

}