【发布时间】:2018-11-26 11:08:29
【问题描述】:
我试图在我的组件中填充一个名为约定的数组,它是一个约定数组。
每个组织都有一个合同列表,每个合同都有一个约定 id,有了这个 id,我就得到了约定。
我使用 getOrganizationForUser 获取当前组织,然后获取合同列表。 然后我使用合约中的约定 id 调用第二个 API 来获取约定。
目前,我的代码如下所示:
public getOrganizationForUser(): Observable<Organization> {
return this.httpClient
.get<Organization>(`${c.serviceBaseUrl.sp}/organizationByUser`)
.pipe(catchError((err, source) => this.responseHandler.onCatch(err, source)));
}
public getById(id: number) {
return this.httpClient
.get<Convention>(`${c.serviceBaseUrl.sp}/conventions/` + id)
.pipe(catchError((err, source) => this.responseHandler.onCatch(err, source)));
}
ngOnInit() {
this.OrganizationService.getOrganizationForUser().subscribe((organization: Organization) => {
organization.contracts.forEach((contract) => {
this.conventionService.getById(contract.conventionId).subscribe((convention: Convention) => {
this.conventions.push(convention);
})
})
})
}
我知道我可以创建一个 observable 数组,并使用 Observable.forkJoin() 等待所有这些异步调用完成,但我希望能够定义订阅回调
每个调用的函数,因为我需要对该过程的引用。关于如何解决这个问题的任何想法?
我试过这个函数,但总是返回了解
getTasksForEachProcess(): Observable<Array<any>> {
let tasksObservables = this.organizationService.getOrganizationForUser().pipe(map((organization: Organization) => {
organization.contractOrganizations.map(contract => {
return this.conventionService.getById(contract.conventionId).subscribe(convention =>
this.conventions.push(convention)
)
});
})
);
return forkJoin(tasksObservables);
};
ngOnInit() {
this.getTasksForEachProcess().subscribe(item => {
console.log(item);
}
}
【问题讨论】:
标签: javascript angular typescript rxjs observable