【问题标题】:RxJs special filteringRxJs 特殊过滤
【发布时间】:2018-11-07 08:39:33
【问题描述】:

我有一段打字稿代码,它调用一个网络服务,然后有选择地(基于类型)将接收到的菜单项附加到一个根菜单项数组中:

private loadMenuItems() {
  this.menuService.getAll().subscribe(menuItems => {

    this.rootMenus.forEach(rootMenu => {
      rootMenu.menus = menuItems
          .filter(menuItem => menuItem.type === rootMenu.rootMenu.type)
          .sort((a, b) => a.showOrder - b.showOrder);

          this.menuItems.concat(rootMenu.menus);
      }, this.errorCallback);

  });
}

我不想在这个方法中订阅 observable,而是返回带有这些数据的 observable。

我该怎么做?

【问题讨论】:

  • return this.menuService.getAll().pipe(...)?
  • 只映射而不是订阅
  • errorCallback是不是放错地方了?现在是 forEach 的第二个参数

标签: typescript rxjs


【解决方案1】:

只需将其通过管道传输到map(和catchError 用于errorCallback)。假设你放错了errorCallback,你会这样做:

private loadMenuItems() {
  return this.menuService.getAll().pipe(map(menuItems => {

    this.rootMenus.forEach(rootMenu => {
      rootMenu.menus = menuItems
          .filter(menuItem => menuItem.type === rootMenu.rootMenu.type)
          .sort((a, b) => a.showOrder - b.showOrder);

          this.menuItems.concat(rootMenu.menus);
      });

  }), catchError(this.errorCallback));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2018-11-23
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多