我有一个 API 调用,我需要进行多次调用,因为该 API 不支持对多个项目的请求。到目前为止,我所写的内容以向服务器发送 GET 请求的无限循环告终。我相信我不理解下面示例中 Observables 的本质。我的假设是 while 循环中的每个调用都会订阅一个新的单个对象,并且当它被解析时,它将被放置在数组中。我怎样才能修改下面的代码来实现我想要的?
getSingle(): Observable<Single> {
return this.http.get(this.url, this.options)
.map((r: Response) => r.json().data as Single);
}
getMultiple(num: number): Single[] {
let multiple: Single[] = [];
let i = 0;
while (i < num) {
this.getSingle().subscribe(single => {
multiple.push(single);
console.log('Success');
i++;
}, err => {
console.log('Failure');
});
}
return multiple;
}
最佳答案
应避免使用 while
循环发出多个异步 HTTP 请求,然后分别订阅所有这些请求,以免打开许多 Observable
连接。我们可以使用 Observable.forkJoin运算符代替。
实现应该是这样的:
getSingle(singleUrl: string): Observable<Single> {
return this.http.get(singleUrl, this.options)
.map((r: Response) => r.json().data as Single);
};
getMultiple(): Observable<Array<Single>> {
let singleUrls = ['singleUrl1', 'singleUrl2', 'singleUrl3']; // can be replaced with any 'Single' identifier
let singleObservables = singleUrls.map((singleUrl: string, urlIndex: number) => {
return this.getSingle(singleUrl)
.map(single => single as Single)
.catch((error: any) => {
console.error('Error loading Single, singleUrl: ' + singleUrl, 'Error: ', error);
return Observable.of(null); // In case error occurs, we need to return Observable, so the stream can continue
});
});
return Observable.forkJoin(singleObservables);
};
this.getMultiple().subscribe(
(singles: Array<Single>) => {
console.log(singles); // [Single, Single, Single];
// In case error occured e.g. for the 'singleUrl' (our 'Single' identifier) at position 1,
// Output wil be: [Single, null, Single];
}
);
希望这对您有所帮助!
关于angular - 发送多个异步 HTTP GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619312/