Abhinav Parashar
Abhinav Parashar

Reputation: 649

How to call a function after previous function is complete in angular

I have 2 functions and I would like to call one after the other

mainFunction(){
this.service1.abc();
this.xyz();
}

this.service1.abc is making an API call to get and setting some data in local storage and based on that this.xyz is using that localStorage value. current behavior : this.xyz() get called before the completion of this.service1.abc() and so on localstorage is not getting set.

API Service function doesn't returns any observable,

Upvotes: 0

Views: 1686

Answers (1)

gil
gil

Reputation: 2552

since the API call function is asyncronous you can't just call it in certain order and expect it to be executed in that order.

if your API Service function returns a promise you can do something like this:

   async mainFunction() {
    await this.service1.abc();
    this.xyz();
    }

which will make the function to wait till your async call has finished then move on to execute the XYZ function.

if your API Service function returns an observable, then your can just subscribe to it and trigger your xyz function like that:

mainFunction(){
this.service1.abc().subscribe(res => {
   this.xyz();
})

}

Upvotes: 2

Related Questions