【问题标题】:AngularFire2 return Observable to ngrx effectsAngularFire2 将 Observable 返回到 ngrx 效果
【发布时间】:2017-06-29 06:29:26
【问题描述】:

我有一个使用 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 })));

服务代码

用户ID:任意; // 声明为任何。如果我尝试将其设为 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;
      }

【问题讨论】:

  • 如果在.ofType(ActionTypes.GET_ACCOUNT_ID) 行之前和之后执行.do(res =&gt; console.log(res)) 会得到什么?
  • 我不认为你的this.userIdObservable
  • 您好,感谢您的快速回复。我不能把它放在那行之前,因为我得到一个编译错误,但是在我得到 Object {type: "GET_ACCOUNT_ID", payload: ""} 之后。我已经解决了问题是什么,只是不知道如何解决它。基本上对 auth 对象的调用是一个订阅,所以它在订阅完成之前返回 this.userId 到效果,所以它返回 this.userId of undefined
  • Harry 是的,你是对的,但我尝试了这个 userId: any; // 声明为任何。如果我尝试将其设为 Observable,那么我会在 this.userId = user.uid; 上收到编译错误。在对 afAuth 的调用中说它不能将字符串分配给 Observable
  • 为什么从getCurrentUserId() 不返回简单的this.afAuth.authState 这是一个可观察的?

标签: angular firebase angularfire2 ngrx


【解决方案1】:

感谢各位大神帮忙,最终解决方案如下:-

效果代码

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

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多