![](/img/trans.png)
[英]Chaining RxJS Observables from http data in Angular2 with TypeScript
[英]What is the proper way to handle concatenation of data returned from multiple http observables in angular2/4 rxjs?
我有 5 個不同的 URL,每個 URL 都返回對象數組中的數據。 我想將這些對象連接到一個數組中,該數組存儲在我的 Angular2 組件本地。 現在,我在我的 ngOnInit 中做這樣的事情:
this.myHttpService.graburl1data()
.subscribe(
response => {
if(!this.mylist) {
this.mylist = []
this.mylist = this.mylist.concat(response);
} else {
this.mylist = this.mylist.concat(response);
}
this.myHttpService.graburl2data()
.subscribe(
response => {
if(!this.mylist) {
this.mylist = []
this.mylist = this.mylist.concat(response);
} else {
this.mylist = this.mylist.concat(response);
}
});
});
必須有更好的方法,請幫助!
您的代碼段似乎表明請求之間沒有依賴關系,因此您可以使用forkJoin
並行執行它們:
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/forkJoin";
Observable.forkJoin(
this.myHttpService.graburl1data(),
this.myHttpService.graburl2data()
)
.subscribe(
(responses) => {
// ... responses[0] is the response from this.myHttpService.graburl1data
// ... etc.
}
);
responses
將是一個responses
數組,按照請求 observable 傳遞給forkJoin
。
如果您希望連續執行請求,請改用concat
和toArray
:
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/concat";
import "rxjs/add/operator/toArray";
Observable.concat(
this.myHttpService.graburl1data(),
this.myHttpService.graburl2data()
)
.toArray()
.subscribe(
(responses) => {
// ... responses[0] is the response from this.myHttpService.graburl1data
// ... etc.
}
);
假設您有兩個請求,每個請求都返回一個發出數組作為流值的 observable:
const response1 = of([1, 2, 3]);
const response2 = of([4, 5, 6]);
您希望將這些值作為值流 - 扁平化。 您可以使用運算符的組合來做到這一點:
const merged = merge(response1, response2).mergeMap((a) => {
return a;
});
merged.subscribe((v) => {
console.log(v);
});
您將獲得以下輸出:
1
2
3
4
5
6
您可以在此處閱讀有關merge
運算符的更多信息。
在您的情況下,您將通過調用http
獲得response
觀察:
const response1 = this.myHttpService.graburl1data(),
const response2 = this.myHttpService.graburl2data()
...
所以,最終的代碼是:
import { merge } from 'rxjs/observable/merge';
import 'rxjs/add/operator/mergeMap';
const merged = merge(
this.myHttpService.graburl1data(),
this.myHttpService.graburl2data()
).mergeMap((a) => {
return a;
});
merged.subscribe((v) => {
console.log(v);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.