【问题标题】:Multiple map() calls in an Angular 6 serviceAngular 6 服务中的多个 map() 调用
【发布时间】:2018-07-24 14:34:31
【问题描述】:

我有一个 HTTP GET 请求,它返回多个我想变成多个可观察对象的对象。以下是响应示例:

{
    lookup1: 
    [
      {
        "label": "lookup1 option 1",
        "value": 1
      },
      {
        "label": "lookup1 option 2",
        "value": 2
      }
    ],
    lookup2: 
    [
      {
        "label": "lookup2 option 1",
        "value": 1
      },
      {
        "label": "lookup2 option 2",
        "value": 2
      }
    ]
}

这是我的服务,它有两个 observables:

this.lookup1 = this.apiService.get('/lookups/')
  .pipe(map(response => response["lookup1"]));
this.lookup2 = this.apiService.get('/lookups/')
  .pipe(map(response => response["lookup2"]));

如何使用一个 HTTP GET 请求完成此操作?

编辑

请注意,这样的代码将执行 2 个 HTTP GET 请求:

let lookups = this.apiService.get('/lookups/');
this.lookup1 = lookups
  .pipe(map(response => response["lookup1"]));
this.lookup2 = lookups
  .pipe(map(response => response["lookup2"]));

【问题讨论】:

  • that returns multiple objects - 我们在这里讨论了多少个对象?此外,如果有 100 个对象——你打算如何将这 100 个可观察对象暴露给它的消费者——这里的目标是什么?
  • 目标是通过一次 API 调用获取应用程序所需的所有查找。

标签: angular rxjs rxjs6


【解决方案1】:

方法一

创建 2 个将在请求解决后更新的主题。

let map1 = new Subject();
let map2 = new Subject();

this.lookup1 = map1.pipe(map(response => response["lookup1"]));
this.lookup2 = map2.pipe(map(response => response["lookup2"]));

this.apiService.get('/lookups/').subscribe( response => { 
   map1.next(response);
   map2.next(response);
})

方法二

您可以使用concatMapfrom 将一个流转换为另一个流。

this.apiService.get('/lookups/').pipe(
  concatMap( responseJson => from(Object.values(responseJson)))
).subscribe( arrayElement=> console.log(arrayElement))

输出:

// first object emitted : 
[
  {
    "label": "lookup1 option 1",
    "value": 1
  },
  {
    "label": "lookup1 option 2",
    "value": 2
  }
]

// second object emitted :

[
  {
    "label": "lookup2 option 1",
    "value": 1
  },
  {
    "label": "lookup2 option 2",
    "value": 2
  }
]

concatMap 接受一个 Observable 并发出另一个 Observable。

来自 将可迭代元素转换为流。您将获得与迭代中的项目一样多的排放量。

【讨论】:

  • 对 observables this.lookup1this.lookup2 的分配在哪里?
  • @Jess 我编辑了Method 1 并插入了this.lookup1this.lookup2
  • 谢谢!它有效,完全让我大吃一惊,但我想我知道map 返回一个可观察的,所以它可以在 GET 请求发生之前“进行分配”。我选择了 方法 1,它看起来更易读...?
猜你喜欢
  • 2018-11-18
  • 2018-11-14
  • 1970-01-01
  • 2019-08-10
  • 2019-03-30
  • 2018-10-21
  • 2016-08-25
  • 2013-04-09
  • 2023-03-27
相关资源
最近更新 更多