使用 Observables 在 Angular 中依次调用两个服务



我正在尝试在Angular中的ngOnIniit上调用两个服务,我有以下代码:

.ts 文件

ngOnInit() {
// Calling 1st service
this.serviceOne.getAllServiceOneData().subscribe(
data => (
this.serviceOneData = data,
console.log('successfully loaded all service one data')
),
error => this.errorMessage =   error as any,
);
//Trying to call 2nd service
if (this.serviceOneData.length > 0) {
this.serviceOneData.forEach(so => {
this.serviceTwo.getAllServiceTwoData(so.id.toString()).subscribe(
data => (
this.serviceTwoData= data,
console.log('successfully loaded service two related data')
),
error => this.errorMessage =   error as any,
);
});  //forEach
}  //if
}

现在,我想订阅第二个服务,并为第一个服务上获取的每个项目获取相关信息。

在Angular 中使用可观察的可能吗?顺便说一句,我正在使用Angular 7。

你应该使用这样的switchMapforkJoin(请参阅注释以获取解释(:

this.serviceOne.getAllServiceOneData()
.pipe(
//Use switchMap to call another API(s)
switchMap((dataFromServiceOne) => {
//Lets map so to an observable of API call
const allObs$ = dataFromServiceOne.map(so => this.serviceTwo.getAllServiceTwoData(so.id.toString()));
//forkJoin will wait for the response to come for all of the observables
return forkJoin(allObs$);
})
).subscribe((forkJoinResponse) => {
//forkJoinResponse will be an array of responses for each of the this.serviceTwo.getAllServiceTwoData CALL
//Do whatever you want to do with this array
console.log(forkJoinResponse);
});

除了forkJoin,您还可以使用concat,具体取决于您的应用程序需求。

希望对您有所帮助。

相关内容

  • 没有找到相关文章

最新更新