使用 RxJS 的 switchMap 操作符将多个 HTTP 调用组合为一个可观察对象,并在组合完成后将其传递给父可观察方法。
示例代码如下:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent {
constructor(private http: HttpClient) {}
getData() {
const getFirstData$ = this.http.get('https://jsonplaceholder.typicode.com/todos/1');
const getSecondData$ = this.http.get('https://jsonplaceholder.typicode.com/todos/2');
Observable.combineLatest(getFirstData$, getSecondData$)
.pipe(
switchMap(([firstData, secondData]) => {
// Do something with the data
console.log('First Data:', firstData);
console.log('Second Data:', secondData);
return this.http.get('https://jsonplaceholder.typicode.com/todos/3'); // Return new observable for parent method
})
)
.subscribe((thirdData) => {
// Do something with the data from the third HTTP call
console.log('Third Data:', thirdData);
// Pass data to the parent method
this.parentHandleData(thirdData);
});
}
parentHandleData(data) {
// Do something with the data in the parent component
console.log('Parent Data:', data);
}
}