3

I have this problem when trying to run in git bash. .switchMap is not geting executed and showing error as" error TS2339: Property 'switchMap' does not exist on type 'Observable' "

The code I am using is:

import { User } from './../classes/user';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { from } from 'rxjs';
@Injectable()
export class AuthService {

  public currentUser: Observable<User | null>;

  constructor(
    private router: Router,
    private alertService: AlertService,
    private afAuth: AngularFireAuth,
    private db: AngularFirestore
  ) {

    this.currentUser = this.afAuth.authState
      .switchMap((user) => {
        if (user) {
          return this.db.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      });
  }

my rxjs version is rxjs@6.3.3 latest and nodejs version is v8.12.0 please help I am building a chat website.

subhajit biswas
  • 261
  • 2
  • 6

2 Answers2

3

Your issue is that in RxJs 6 the switchMap (along with many other operators) no longer exists on the Observable. Instead you have to pipe the observable using the .pipe() operator which takes any amount of methods and applies them to the observable. You then import the switchMap function to use it in the pipe..

import { switchMap } from 'rxjs/operators';

....

this.currentUser = this.afAuth.authState.pipe(
  switchMap((user) => {
    if (user) {
      return this.db.doc<User>(`users/${user.uid}`).valueChanges();
    } else {
      return of(null);
    })
);

If you're used to the old (RxJs 5) behaviour and you would like to work that way there is a package called rxjs-compat (install it with npm install rxjs-compat) which allows you to use RxJs 6+ with the old syntax.

However there are major performance and bundle size gains from using the newer syntax, because it supports Tree Shaking, so I would not recommend it.

Daniel
  • 10,641
  • 12
  • 47
  • 85
1

I know this is a very late response, but I got a similar error. For me even the Answer of @Daniel did not work. I had to use the pipe in a seperate statement:

...
this.currentUser = this.afAuth.authState;
this.currentUser.pipe(switchMap(user => {
    if (user) {
      // logged in, get custom user from Firestore
      return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
    } else {
      // logged out, null
      return of(null)
    }
}))

Alongside that, I encountered some troubles importing switchmap, of and Observable, but managed to get everything imported with:

import { Observable } from 'rxjs';
import { of } from 'rxjs';
import {switchMap} from 'rxjs/operators';

The code worked fine under

  • Angular CLI: 7.3.8
  • Node 10.15.3
  • Angular 7.2.14
  • rxjs: 6.5.1
Luca Knaack
  • 107
  • 8