[英]RXJS How do I use the result of one observable in another (and then process those two results together)
[英]How to use two observable functions one inside another with loop in rxjs?
我有一個名為processList(request)
可觀察函數,它返回頁面內的進程列表,我需要獲取每個返回進程的鏈接進程列表,為此我使用另一個可觀察函數,它返回給定進程的鏈接進程列表linkedProcessesList(process.id)
,所以像這樣:
let listOfProcesses = [];
let listOfLinkedProcesses = [];
this.processEndpoint.processList(request).subscribe(result => {
//getting list of processes for that page
listOfProcesses = result.data;
// now i need to get list of linked processes for each process in the listOfProcesses array
listOfProcesses.forEach(process => {
this.processEndpoint.linkedProcessesList((process.id).subscribe(result1 => {
// here how do i populate listOfLinkedProcesses array?
// this.processToProcessLinkList.push(...result1.data); <- this doesn't work gives an error
}
});
}
}
您可以將switchMap
與forkJoin
一起使用。 嘗試以下
this.processEndpoint.processList(request)
.pipe(
map(result => {
this.listOfProcesses = result.data;
return linkedProcesses = result.data.map(item => this.processEndpoint.linkedProcessesList(item.id));
}),
switchMap(linkedProcessesObservables => forkJoin(linkedProcessesObservables))
)
.subscribe(linkedProcessesResult => {
this.listOfLinkedProcesses = linkedProcessesResult;
});
我沒有測試代碼,所以可能有一些問題需要解決。
使用forkJoin
,您可以請求multiple requests
。 它就像Promise.all
但用於observable
。
let character = this.http.get("https://api.co/api/people/1");
let characterHomeworld = this.http.get("http://api.co/api/planets/1");
forkJoin([character, characterHomeworld]).subscribe(results => {
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.