I am 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();
Upon its success implementation I need to do the same with all another maps 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().
Can anyone help me with that? Thanks in advance!
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:
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));
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.