Exp*_*lls 5 rxjs typescript angular
我有一个应用程序,它发出一个http请求来获取项目列表,然后为列表中的每个项目发出一个http请求,以获取有关每个项目的更多详细信息.有效:
class ItemsService {
fetchItems() {
return this.http.get(url)
.map(res => res.json())
.map(items => items.map(this.fetchItem(item)));
}
fetchItem(item: Item) {
this.http.get(`${url}/${item.id}`)
.map(res => res.json());
}
}
Run Code Online (Sandbox Code Playgroud)
然后我会做类似itemsService.fetchItems().subscribe(items => console.log(items))但最终发生的事情是我得到一个可观察数组(每个响应来自fetchItem).我还需要订阅每个内部可观察对象,以便fetchItem实际触发请求.
我也试过使用flatMap而不是map,但在这种情况下似乎有相同的结果.是否有任何方法可以订阅嵌套的observable?
我会这样做:
function mockRequest() {
return Observable.of('[{"id": 1}, {"id": 2}, {"id": 3}]');
}
function otherMockRequest(id) {
return Observable.of(`{"id":${id}, "desc": "description ${id}"}`);
}
class ItemsService {
fetchItems() {
return mockRequest()
.map(res => JSON.parse(res))
.concatAll()
.mergeMap(item => this.fetchItem(item));
}
fetchItem(item: Item) {
return otherMockRequest(item.id)
.map(res => JSON.parse(res));
}
}
let service = new ItemsService();
service.fetchItems().subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)
查看现场演示:http://plnkr.co/edit/LPXfqxVsI6Ja2J7RpDYl ?p=preview
我正在使用一种技巧来.concatAll()将对象数组转换为[{"id": 1}, {"id": 2}, {"id": 3}]逐一发出的单独值{"id": 1},{"id": 2}并且{"id": 3}(到目前为止,这是一项未记录的功能)。然后我用来mergeMap()在单独的请求中获取它们的内容并将其结果合并到运算符链中。
此 plnkr 示例打印到控制台:
{ id: 1, desc: 'description 1' }
{ id: 2, desc: 'description 2' }
{ id: 3, desc: 'description 3' }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5172 次 |
| 最近记录: |