In my Angular2 project, I have a service that fetches data for dropdown menus on a form. However, when I call this service multiple times with different parameters in the form component initialization, only the last call seems to work, overriding the previous ones. It appears that subsequent calls are canceling out the previous fetches.
To tackle this issue, I separated each call into its own function. But now I need a way to execute these functions sequentially so that each one waits for the previous one to complete. Although each function works independently, calling more than one at a time causes errors as the current fetch is terminated when new parameters are passed.
this.fetchValueListOne();
this.fetchValueListTwo();
this.fetchValueListThree();
I initially tried using promises but ran into scoping problems while passing services and retrieving data. Each service call has three parameters and assigns data to a specific variable in the component used by the form.
Another attempt involved creating a list of functions as variables and iterating over them. However, similar scoping issues arose as with promises.
The service returns an Observable, which the functions subscribe to, retrieve data from, and assign to an array variable bound to a dropdown value list in the component.
Here is an example of how these functions look:
fetchValueListOne() {
this.dataSvc.getValueList('Val-List-One', this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
.map(response => response.json())
.subscribe(
data => {
this.valListOne = data;
},
err => console.log('Error', err),
() => {
console.log('this.valListOne', this.valListOne);
}
);
}