I have a service in Angular 2 that contains a function responsible for providing data for a dropdown list. This particular function returns a promise.
Below is the code snippet from the service:
getStuff(): Promise<Stuff>
{
return this.http.get("http://myserver/myServices/myService.svc/rest/getStuff")
.map(res => this.dataHandler.extractData(res)).toPromise()
.catch(err => this.dataHandler.handleHttpError(err));
}
During a save event, I call this function to update the newly saved data, ensuring that the dropdown list utilizing this data remains current.
The following is the code where I invoke this service:
ngOnInit()
{
this.onSavedSubscription = this.OnSaved.subscribe((data: any) =>
{
if (data.IsSuccessful)
{
this.myService.getStuff().then(
res=>
{
this.myService.stuffs = res;
}
);
}
}
Upon executing the above code, the getStuff function is invoked. However, before it can return the updated data fetched from the database, the execution jumps to "then" and populates this.myService.stuffs with outdated data present in res. This behavior has left me confused. I was under the impression that "then" would only execute after the completion of getStuff and the retrieval of new data. Any assistance would be greatly appreciated.