14
votes

I have been getting the following error message when trying to apply the switchMap operator to my Observable:

Property 'switchMap' does not exist on type 'Observable'.

I'm currently using rxjs version 5.5.2, and in my component, I have it imported like so:

import 'rxjs/operator/switchMap';

However, I still get a compilation error. I have looked at similar questions and have not found a proper solution to this, any suggestions on what could be the issue here?

get appUser$() : Observable<AppUser> {
  return this.user$
    .switchMap(user => {
      if (user) return this.userService.get(user.uid);

      return Observable.of(null);
    });    
}

Image: enter image description here

3

3 Answers

15
votes

You should be importing from rxjs/add/operator/switchMap if you're using the older "patch" style of operators:

import 'rxjs/add/operator/switchMap';

Since RxJS 5.5 with "pipable" operators you should import from 'rxjs/operators':

import { switchMap } from 'rxjs/operators';
19
votes

I assume you're using Angular 6, which mean you're using the latest version of RxJS. You need to pipe your operators as

obs$.switchMap(() => { do stuff... });

change to

obs$.pipe(switchMap(() => { do stuff... }));

Edit: keep in mind that in your case, your observable is returned by this.refreshToken

this.refreshToken().pipe(switchMap(() => { do stuff... }));
4
votes

I think If you are using Angular 6 then you should use pipe

Version less than angular 6, the below code will works

        this.route.params.switchMap((data: Passengers) => 
        this.passengerService.getPassenger(data.id))
        .subscribe((data: Passengers) =>  this.passenger = data);

But for In Angular 6, you should pipe your operators

    this.route.params.pipe(switchMap((data: Passengers) => 
    this.passengerService.getPassenger(data.id)))
    .subscribe((data: Passengers) =>  this.passenger = data);