Home > OS >  How to call another service/api only if the first one has successfully executed?
How to call another service/api only if the first one has successfully executed?

Time:09-23

very new to angular and typescript. I have been trying this.

doSomething() {
    return this.http.post(this.path   "dosomething", data).toPromise();
}

now in .ts you are awaiting it

await servicesCalls.doSomething();

now upon its success implementation I need to all another map from service.

but first i want to make sure it has posted the data.

await serviceCalls.doAnotherThing();

The api is returning IHTTPACTIONRESULT i.e. Ok().

CodePudding user response:

Use switchMap

doSomething() {
    return this.http.post(this.path   "dosomething", data);
}


doAnotherthing() {
    return this.http.post(this.path   "dosomething", data);
}

doSomething().pipe(
  tap(doSomethingResponse => this.performSomeOperation(doSomethingResponse)),
  switchMap(_ => this.doAnotherthing())
).subscribe(doAnotherthingResponse => console. log(doAnotherthingResponse));

CodePudding user response:

There is no need to use promises. HTTP methods in Angular return an Observable. You can subscribe to that observable, an when that observable emits some data then in the subscribe method you can call another service.

Something like this::

doSomething() {
    return this.http.post(this.path   "dosomething", data);
}

Now there are various different ways to do this:

Method one: Normal way. Call another service in the subscription of the first one.

Component:

public callService() {
    doSomething.subscribe(data => {
        serviceCalls.doAnotherThing();
    },
    err => {
        // do something
    })
}

Subscription will only be called when doSomething function( that is your HTTP request returns some value).

Method 2: You can use rxjs operators - switchMap like this:

doSomething()
    .pipe(
        //Use switchMap to call another API(s)
        switchMap((dataFromServiceOne) => {
            serviceCalls.doAnotherThing();
        })
    ).subscribe((data) => {
        // do something with response
        console.log(data);
    });

For more details about rxjs operators:

  1. switchMap
  2. Observables

CodePudding user response:

when using angular http client, you'd typically subscribe to the observable as mentioned in @Drashti Dobariya's answer. when using async/await, you might as well just use fetch.

when awaiting something, the program flow continues after the awaited promise resolved. what you probably want is a check, if the http request succeeded:

let response = await servicesCalls.doSomething();

// you may have to handle different status codes
if (response.status != 200) {
  return;
}

response = await serviceCalls.doAnotherThing();

CodePudding user response:

You could simply store this in a variable like this,

const promise = servicesCalls.doSomething();

and simply call the next one like this,

promise.then(async () => await serviceCalls.doAnotherThing()).catch(e => console.error(e));

The next API call will only be executed when the previous promise resolves.

CodePudding user response:

    **service**
    
    post(data:any){
    return this.http.post(`${baseUrl}/post`, data)
    }
    get(){

return this.http.get(`${baseUrl}/post`)
}

**In component.ts**

constructor(private service: Service){}

postData(){
let data = {}
this.service.post(data).subscribe(res=>{
  if(res.length > 0){
  this.service.get().subscribe(res=>{
  console.log('data get successfully')
})
}
})
}
  • Related