I am facing a situation where I must iterate through a loop to retrieve the descriptions of respective items. These descriptions need to be included in a datatable along with the item Ids and other details.
addDescription(){
this.arrayOfItems.forEach(element => {
// CALL a function for making a service call
this.fetchDescription(element);
//CODE TO DECLARE AN INTERFACE FOR ASSIGNING VALUES, e.g.
// ITEM_ID : element.id,
// ITEM_DEF : this.fetchedDescription.join("\n")
}
Function body:
fetchDescription(elementToFetchDesc){
//Declare HTTPPARAMS in PassingParams variable
this.componentService.getDesc(PassingParams)
.subscribe((response: HttpResponse<any>) => {
if(response.status ==200){
this.fetchedDescription = reponse.body.output.slice(6,-1);
}
//Code if response status is NOT 200
}
In componentService
Service:
construcutor(private httpConn: HttpClient){}
getDesc(Params){
// Declare URL
return this.httpConn.get(URL, {params: Params, observe: 'response'});
}
The challenge:
Due to the asynchronous nature of the subscription within the loop, the description is not being assigned to the variable (ITEM_DEF
) in the interface after running the loop using forEach
.
To address this issue, I made a slight modification by implementing the use of promise
.
In the service, I added:
import 'rxjs/add/operator/toPromise';
And updated the service method as follows:
return this.httpConn.get(URL, {params: Params, observe: 'response'})
.toPromise(); // converted observable to promise
Also, I made a change in the component:
Within the fetchDescription
function:
replaced .subscribe
with .then
However, the issue still persists. I would appreciate any insights on where I may have gone wrong in implementing this logic.