我有一个从 firebase 的 authState 用户获取的操作。如果用户存在,则代码返回与用户相关的文档。如果没有,of(null)
将被退回:
类 AuthState
ngxsOnInit({dispatch}: StateContext<AuthStateModel>) {
dispatch(SyncAuth);
}
@Action(SyncAuth)
syncAuth({dispatch}: StateContext<AuthStateModel>) {
return this.afAuth.authState.pipe(
switchMap(fireAuth => fireAuth ? this.authService.auth$(fireAuth.uid) : of(null)),
tap(user => dispatch(new PatchUserData(user)))
);
}
类 AuthService
auth$(userId: string): Observable<User> {
if (!userId) {
return of(null);
}
return this.db.doc$(`users/${userId}`).pipe(
map(user => user ? this.transform({...user, id: userId}) : null),
shareReplay(1)
);
}
看起来很简单,对吧?好吧,除非你的 Redux Devtools 插件打开(是的,我知道这很奇怪),否则它不会工作。
当我想在 switchMap 运算符中返回具有任何类型(例如数字、字符串、null 甚至未定义)的值的 observable 时,我收到以下错误:
未捕获的类型错误:您在预期流的位置提供了无效对象。您可以提供 Observable、Promise、Array 或 Iterable。(zone.js:192)
at subscribeTo (subscribeTo.js:41) at subscribeToResult (subscribeToResult.js:6) at SwitchMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/switchMap.js.SwitchMapSubscriber._innerSub (switchMap.js:47) at SwitchMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/switchMap.js.SwitchMapSubscriber._next (switchMap.js:40) at SwitchMapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at angularfire2.js:49 at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388) at Object.onInvoke (core.js:3820) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
有问题的行在我的AuthState
课上:
// fireAuth === null
switchMap(fireAuth => fireAuth ? this.authService.auth$(fireAuth.uid) : of(null)),
但是,如果我删除of
运算符并返回authService.auth$
observable 的结果(返回of(null
),那么错误就消失了: