I want to execute two statements together, but not in asynchronous. Is there a way to execute function 1 first before function 2 in angular2?
-
8Please post the code that demonstrates what you try to accomplish, what you tried, and where you failed. Your question doesn't provide enough information.Günter Zöchbauer– Günter Zöchbauer2017-06-14 15:53:06 +00:00Commented Jun 14, 2017 at 15:53
1 Answer
We may need more info but let say you have 2 http calls and you want make them "synchronous" (one first and then the second one). I would recommend using ReactiveX JavaScript, you can import by including:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/mergeMap';
With mergeMap operator you are able to start a "second task" (new observable) taking the first one's result as input.
So, for instance, I need to check address before updating my user profile. I have 2 http calls; one for the address check and another one for updating the user profile, so I would do:
this.http.get(geolocationGoogleUrl, this._customAddress)
.mergeMap((location: any)=>{ // First http response
console.log(location);
// Do your stuff before second call
return this.http.patch(patchUrl, localAddress); // Use frist http response as input
}).subscribe((updatedUser)=>{ // Second http response
this._user = updatedUser;
});
As you noticed, you need to subscribe to a observable in order to trigger the call.