Property 'switchMap' does not exist on type 'Observable<User>'

匆匆过客 提交于 2020-03-18 04:01:07

问题


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:


回答1:


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';



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/48873748/property-switchmap-does-not-exist-on-type-observableuser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!