Reputation: 89
I am working with Angular 10 and trying to handle multiple API calls using forkJoin. The API calls are defined inside a function where I also need to process the API result and then resolve each promise. I want to achieve the combined result of all these functions to be returned. However, the forkJoin is never resolved. What am I doing wrong. My code is as below:
const promises = [];
for (let i = 0; i < bulkImportSets.length; i++) {
promises.push(
this.policyService.importPolicy({files: bulkImportSets[i]}, this.selectedFiles)
);
}
this.value$ = forkJoin(promises);
importPolicy( policies, filesMetadata): Observable<any> {
let result: { data: { items: { data: any[]; result_code: string } } } = null;
return new Observable( (observer) => {
const url = `${COMMON.LEGACY_API_PATH}sep/import/policy`;
/*
* This is done this way to send data via multipart/form-data
* */
const fd = new FormData();
fd.append('policies', new Blob([JSON.stringify(policies)], {
type: 'application/json'
}));
this.baseService.postData(url, fd).subscribe(
(resolve) => {
result = resolve['data'];
observer.next(result);
},
(error) => {
result = getServiceFailureResponseJson(policies, filesMetadata, error);
observer.next(result);
}
);
} );
}
In error case the data needs to be transformed using 'getServiceFailureResponseJson' and still resolved.
postData is an http client call method:
postData(url: string, data?: any, params?: any): Observable<import("@angular/common/http").HttpEvent<any[]>>;
Upvotes: 0
Views: 563
Reputation: 12206
fixed importPolicy method would be
importPolicy( policies, filesMetadata): Observable<any> {
const fd = new FormData();
fd.append('policies', new Blob([JSON.stringify(policies)], {
type: 'application/json'
}));
return this.baseService.postData(url, fd).pipe(
map(resolve => resolve.data),
catchError(error => of(getServiceFailureResponseJson(policies, filesMetadata, error)))
);
}
the difference from your code is that it is written using rxjs fns and it automatically completes itself. All other behavior is the same
Upvotes: 1