如何结合两个可观察角度的结果?
this.http.get(url1)
.map((res: Response) => res.json())
.subscribe((data1: any) => {
this.data1 = data1;
});
this.http.get(url2)
.map((res: Response) => res.json())
.subscribe((data2: any) => {
this.data2 = data2;
});
toDisplay(){
// logic about combining this.data1 and this.data2;
}
Run Code Online (Sandbox Code Playgroud)
以上是错误的,因为我们无法立即获取data1和data2.
this.http.get(url1)
.map((res: Response) => res.json())
.subscribe((data1: any) => {
this.http.get(url2)
.map((res: Response) => res.json())
.subscribe((data2: any) => {
this.data2 = data2;
// logic about combining this.data1 and this.data2
// and set to this.data;
this.toDisplay();
});
});
toDisplay(){
// display data
// this.data;
}
Run Code Online (Sandbox Code Playgroud)
我可以在第二个observable的subscribe方法中组合结果.但我不确定达到我的要求是否是一个好习惯.
更新:
我发现的另一种方法是使用forkJoin
组合结果并返回一个新的observable.
let o1: Observable<any> = this.http.get(url1)
.map((res: Response) => res.json())
let o2: Observable<any> = this.http.get(url2)
.map((res: Response) => res.json());
Observable.forkJoin(o1, o2)
.subscribe(val => { // [data1, data2]
// logic about combining data1 and data2;
toDisplay(); // display data
});
toDisplay(){
//
}
Run Code Online (Sandbox Code Playgroud)
Gra*_*ham 23
一个很好的方法是使用rxjs forkjoin操作符(它包含在Angular btw中),这使你远离嵌套的异步函数地狱,你必须在函数后使用回调嵌套函数.
这是一个关于如何使用forkjoin(以及更多)的精彩教程:
https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs
在示例中,您创建了两个http请求,然后在订阅胖箭头函数中,响应是一个结果数组,您可以根据需要将它们组合在一起:
let character = this.http.get('https://swapi.co/api/people/1').map(res => res.json());
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1').map(res => res.json());
Observable.forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
Run Code Online (Sandbox Code Playgroud)
数组中的第一个元素始终对应于您传入的第一个http请求,依此类推.几天前我成功地使用了这个,同时有四个请求,它运行得很好.
如果它不起作用,请尝试使用 forkJoin,然后尝试mergeLatest() 它的作用 - 它会在流数组完成之前将流数组中最后发出的值合并到一个值中。
Observable.combineLatest(
this.filesServiceOberserval,
this.filesServiceOberserval,
this.processesServiceOberserval,
).subscribe(
data => {
this.inputs = data[0];
this.outputs = data[1];
this.processes = data[2];
},
err => console.error(err)
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19733 次 |
最近记录: |