首页 > 解决方案 > RxJS 6 switchMap 不推荐使用的符号

问题描述

我已经从 更新Angular 5Angular 6。现在我正在尝试更新我的代码以使其与RxJS 6.

.pipe(
  map(job => job[0]),
  switchMap((job) => {
    return job ? this.bookingService.findByID(job.property.id) : Observable.empty();
  }, (job: Job, bookings: Booking[]) => {
    this.mark_jobs_unavailable(job, bookings);
    return job;
  })
)

我收到关于使用 switchMap 的警告Deprecated Symbol is used

这些是我的进口:import {map, switchMap} from 'rxjs/operators';

有没有其他方法可以在 v6 中使用 switchMap?此外,如果我不更改我的代码rxjs-compat应该使我现有的代码工作(我已经安装)但我得到以下错误,使用相同的代码但在 RxJS 5 样式:

.map(job => job[0])
.switchMap((job) => {
    return job ? this.bookingService.findByID(job.property.id) : Observable.empty();
}, (job: Job, bookings: Booking[]) => {
    this.mark_jobs_unavailable(job, bookings);
    return job;
})

Error: Expected 1 argument but got 2.

标签: angularrxjsangular5angularfire2angular6

解决方案


作为第二个参数给出的 resultSelector 函数switchMap弃用。您需要删除它并使用map运算符实现目标。

这里最棘手的部分是决定将map操作符放在哪里。实际上 map 操作符进入作为参数提供的函数体内部switchMap

没有结果选择器功能的代码将类似于以下内容:

     .pipe(
          map(job => job[0]),
          switchMap((job) => {
            return (job ? this.bookingService.findByID(job.property.id) : Observable.empty()).pipe(

              // This is the mapping function provided as the alternative to the deprecated result selector function
              // This should be placed inside the body of the function which is the 1st (and only one) argument of switchMap
              map((bookings: Booking[])=>{
              this.mark_jobs_unavailable(job, bookings);
              return job;
            })

            );
          }     
         )
        )

推荐阅读