Angular 如何在执行代码块之前等待多个异步http调用返回
我知道forkJoin,但我的问题与下面的代码不同Angular 如何在执行代码块之前等待多个异步http调用返回,angular,typescript,Angular,Typescript,我知道forkJoin,但我的问题与下面的代码不同 getAllData() { let riskTable = this.getRiskTable(); let risks = this.getAllRisks(); // should also return some observable forkJoin(riskTable, risks).subscribe(_ => { // all observables h
getAllData() {
let riskTable = this.getRiskTable();
let risks = this.getAllRisks(); // should also return some observable
forkJoin(riskTable, risks).subscribe(_ => {
// all observables have been completed
});
}
我在每个subscribe方法中都做了大量的计算,http调用是从不同的方法中进行的,计算是在该方法本身中完成的。我不能将所有这些方法合并到一个方法中,因为这将导致代码重复,因为我需要在多个位置分别调用这些方法
例:
现在,我需要在方法中所有这些http调用返回后执行一段代码
this.getAllPartners()
this.getAllUoms();
this.getAllproductsByLocation();
this.getAllLocations();
this.getAllOperationTypes();
i、 e.所有这些方法调用返回后,以及它们内部的异步回调完成后
,如何实现这一点?这里可以使用ForkJoin。您可以返回可观察对象并使用forkJoin,而不是订阅每个get函数
getAllLocations(){
return this .queryResourceService.
getAllLocationsForTransfersUsingGET(this.allLocParams);
}
getAllPartners(){
this.spinner.show();
this.queryResourceService.getAllPartnersUsingGET(this.partnerParams);
}
...
然后在恩戈尼特
ngOnInit(){
forkJoin(
this.getAllLocations()
this.getAllPartners();
...
)
.subscribe(([locations, partners, ...]) => {
this.handleLocationSubscription(locations);
this.handlePartnerSubscription(locations);
...
// Perform task after all async operatiojns resolved
});
}
handleLocationSubscription(data: LocationDTO[]) {
this.locationDTOs = data;
...
}
您不必单独订阅每个HTTP可观察对象。您可以使用RxJS(或)、运算符在每个HTTP请求中进行计算,并返回可观察的结果
从'rxjs'导入{of,forkJoin};
从“rxjs/operators”导入{map、tap、finalize、catchError};
getAllLocations(){
返回此.queryResourceService.GetAllLocationsfortTransferusingGet(this.AllLocalParams).pipe(
地图((数据:LocationDTO[])=>{
this.locationDTOs=数据;
返回数据;//{
控制台日志(“错误”);
返回(错误);//{
控制台日志(“错误”);
返回(错误);//{
控制台日志(“错误”);
返回(错误)/{},
()=>this.spinner.hide();
);
}
现在,您有了一个单一的订阅源,可以集中控制
微调器
标志。因此,当多个请求正在进行时,它不会在显示和隐藏状态之间切换。如果您希望在每个可观察对象单独完成时执行某些操作,那么您可以将管道引入操作符和其他操作符。谢谢或者这一行的答案返回(错误)
导致预期表达式
error@Arjun:请将所有console.log(“error”),
替换为console.log(“error”);
。请注意逗号改为分号。我无意中在语句末尾添加了逗号,而不是分号。
ngOnInit(){
forkJoin(
this.getAllLocations()
this.getAllPartners();
...
)
.subscribe(([locations, partners, ...]) => {
this.handleLocationSubscription(locations);
this.handlePartnerSubscription(locations);
...
// Perform task after all async operatiojns resolved
});
}
handleLocationSubscription(data: LocationDTO[]) {
this.locationDTOs = data;
...
}