【发布时间】: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 => console.log(res))会得到什么? -
我不认为你的
this.userId是Observable。 -
您好,感谢您的快速回复。我不能把它放在那行之前,因为我得到一个编译错误,但是在我得到 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