Search code examples
angulartypescriptrxjsangularfire2ngxs

NGXS - Provided invalid object while return of(any) in switchMap


I have an action that gets from firebase's authState the user. If the user exists, then the code returns the document related to the user. If not, of(null) would be returned:

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

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

Looks simple, right? Well, it's not going to work, unless your Redux Devtools plugin is on (Yeah, I know it's weird).

When I want to return an observable with a value of any type (such as number, string, null or even undefined), inside the switchMap operator, I get the following error:

Uncaught TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or 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)

The problematic line is in my AuthState class:

// fireAuth === null
switchMap(fireAuth => fireAuth ? this.authService.auth$(fireAuth.uid) : of(null)),

But, if I remove the of operator and return the result of authService.auth$ observable (which returns of(null), then the error's gone:


Solution

  • Sometimes, we put lots of trust in our IDEs. Sometimes we shouldn't. My IDE imported the operator this way:

    import { of } from 'rxjs/internals/operators';
    

    instead of

    import { of } from 'rxjs';