0

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?

1
  • 8
    Please post the code that demonstrates what you try to accomplish, what you tried, and where you failed. Your question doesn't provide enough information. Commented Jun 14, 2017 at 15:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.