Reputation: 2662
I have a common service to make http call.
The first http call is to get token and with the updated token the second request is made. But user will call the doPost()
method only.
And the user should be able to resolve the promise it in the component.
public getToken(){
return this.http.get(<url>);
}
public doPost(){
this.getToken().subscribe(token => {
return this.http.post(<url>,token);
});
}
The post method return is not working. How to return the promise of the second call after the first call is success.
Upvotes: 1
Views: 44
Reputation: 166
You can try
import {switchMap} from 'rxjs/operators';
public getToken(){
return this.http.get(<url>);
}
public doPost(){
return this.getToken().pipe(switchMap(token => this.http.post(<url>,token)));
}
And call function doPost().toPromise();
or doPost().subscribe();
Upvotes: 1
Reputation: 368
You don't have to use subscribe
twice, just use pipe
:
public getToken(){
return this.http.get(<url>);
}
public doPost() {
this.getToken().pipe(
mergeMap(token => this.http.post(<url>, token))
)
}
now you should be able to get the answer to the post
method:
this.doPost.subscribe(res => <do something with the res>);
Upvotes: 1
Reputation: 1547
You should use an observable as well as subscribe to it. Unless you want specifically a promise, by default it is an observable and it should stay like that. Now you are not returning anything from doPost. it should be something like this:
public getToken(){
return this.http.get(<url>);
}
public doPost(){
var result: Subscription = this.getToken().subscribe(token => {
return this.http.post(<url>,token);
});
}
And then you can resolve this subscription and get back another observable if you want it like that.
If you want specifically a promise you "toPromise()" on an observable result.
What I would do in your place is subscribe to an observable in the class you are using the result of it and assigne a variable you use inside that class as soon as the result is back, or resolve i in the async pipe in the html part of it.
Something like this should give you a clue:
public getToken(){
return this.http.get(<url>);
}
public doPost(){
this.getToken().subscribe(token => {
this.yourvariable = this.http.post(<url>,token);
});
}
Or
<div *ngFor="let x in yourVariable | async"></div>
Upvotes: 0