AngularFire2将Observable返回到ngrx效果

时间:2017-06-29 06:29:26

标签: angular firebase angularfire2 ngrx

我有一个使用Angular 4,ngrx和AngularFire2构建的项目。我正在尝试检索当前登录用户的uid并将其放入我的商店。

任何想法或帮助都将不胜感激。

错误

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 })));

服务代码

userId:any; //声明为任何。如果我试图使这成为一个Observable然后我得到一个编译错误this.userId = user.uid;在对afAuth的调用中说它不能将字符串赋给Observable

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;
      }

1 个答案:

答案 0 :(得分: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;

}