Reputation: 12005
I have two Observable
requests to server:
this.initService.__init__(res).subscribe((profile) => {
console.log(profile); // It works
this.initService.initializePeriod(profile).subscribe((period) => {
console.log(period); // It does not work
});
});
When first gets response it calls second, but I can not get result for second subscribe. I know, better to use Promises in this case, but I need pass result from first request to second, promises dont allow to do this.
I tried to use this, but Alert message does not work:
this.initService.__init__(res)
.pipe(
mergeMap(profile => this.initService.initializePeriod(profile)))
.subscribe((response) => {
alert('aa');
});
Also tried this:
this.initService.__init__(res)
.mergeMap(profile => this.initService.initializePeriod(profile))
.subscribe((response) => {
alert('aa');
});
Upvotes: 1
Views: 1132
Reputation: 5301
You need to check the result that you are getting from your first API call (profile). Check your browser console. Chances are that the profile is probably a JSON, not a valid URL. The request will not go through if the URL is not valid.
If you provide a valid URL, API call inside another API call should work.
Upvotes: 0
Reputation: 11243
You can use switchMap
rxjs operators to chain the observables.
import { switchMap } from 'rxjs/operators';
this.initService.__init__(res)
.pipe(
switchMap(profile=> this.initService.initializePeriod(profile))
).subscribe((period) => {
console.log(period);
});
If you want to have response from both then use mergeMap
import { mergeMap } from 'rxjs/operators';
this.initService.__init__(res)
.pipe(
mergeMap(
profile=> this.initService.initializePeriod(profile),
(profile, period) => {
return [profile,period];
}
)
).subscribe((response) => {
console.log(response[0]); //profile
console.log(response[1]); //period
});
Working copy is here - https://stackblitz.com/edit/typescript-wy26a7
Upvotes: 2