首页 > 解决方案 > Angular Rxjs:使用管道运算符的语法错误

问题描述

我正在尝试重新编写此代码:

Observable
    .merge(this.searchQuery$, this.lazyQuery$)
    .do(() => this.loadingPage())
    .map(filter => this.buildURL("jaume", Config.security['appName'], filter))
    .switchMap(url =>
        this.service.getItemsFromStorage(url)
        .map(response => this.buildPage(response))
        .catch(() => Observable.of(pojo.Page.EMPTY))
    )
    .do(page => this.loadedPage(page))
    .takeUntil(this.unsubscribe$)
    .subscribe();

我想使用“pipable”语法。到目前为止,我已经能够写出:

this.searchQuery$.pipe(
    merge(this.lazyQuery$),
    tap(() => this.loadingPage()),
    map(filter => this.buildURL("jaume", Config.security['appName'], filter))
)
.pipe(
    switchMap(url => this.service.getItemsFromStorage(url)),
    catchError(() => Observable.of(pojo.Page.EMPTY))
)
.pipe(
    tap(page => this.loadedPage(page))  <<***>>
);

我收到编译器错误<<***>>

'响应 | 类型的参数 “页面”不可分配给“页面”类型的参数。“响应”类型缺少“页面”类型的以下属性:总计、用户

似乎catchError是返回{} | Page类型,当它应该返回一个Page类型时。

有任何想法吗?

标签: angulartypescriptrxjs

解决方案


您错过了将 a 映射response到 a page

merge(this.searchQuery$, this.lazyQuery$).pipe(
  tap(() => this.loadingPage()),
  map(filter => this.buildURL("jaume", Config.security['appName'], filter)),
  switchMap(url => this.service.getItemsFromStorage(url).pipe(
    map(response => this.buildPage(response)), // <-- you missed this map in your code
    catchError(() => of(pojo.Page.EMPTY))
  )),
  tap(page => this.loadedPage(page)),
  takeUntil(this.unsubscribe$)
).subscribe();

另请查看官方迁移指南:Howto: Convert to pipe syntax


推荐阅读