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[]>>;
.nextis not enough. you should also.completeyour observables. add acompletecall afternextand it will work. also in most cases if you are usingnew Observable(...constructor, you are probably doing something wrong. there are a lot of methods/operators that do that work for you