我正在开发一个组件,需要并行调用两个API。并且我只想在API调用都被解析时调用一个方法。
ngOnInit() {
this.serviceOne.someApi().subscribe((res) => {
this.response1 = res;
});
this.serviceTwo.someApi().subscribe((res) => {
this.response2 = res;
});
}
我只想在填充this.response1
和this.response2
时调用一个方法。
目前,我正在用一个if statement
包装方法中的逻辑。
someMethod() {
if(this.response1 && this.response2) {
//logic
}
}
并将CCD_ 4放入两个api调用的CCD_。
实现这一目标的最佳方式是什么
您可以使用forkJoin来实现它。
尝试如下:
工作演示
ngOnInit() {
const request1 = this.serviceOne.someApi();
const request2 = tthis.serviceTwo.someApi();
forkJoin([request1, request2]).subscribe(data => {
this.response1 = data[0];
this.response2 = data[1];
this.someMethod();
});
}
与数组析构函数的答案相同。
forkJoin([
this.serviceOne.someApi(),
this.serviceTwo.someApi(),
]).subscribe(data => {
let [serviceOneResponse, serviceTwoResponse] = data;
// use responses.
});