我有一个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
}
]
}
这是我的服务,可得到两个可观察值:
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"]));
答案 0 :(得分:3)
方法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);
})
方法2
您可以使用concatMap
和from
将流转换为另一个流。
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。
来自 将可迭代元素转换为流。您将获得与迭代中的项目一样多的排放。