In my Angular 2 app I have backend service as below.
getUserInterests() {
return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());
}
After calling this service I want to call another service on success of previous one.
2nd service
let params: URLSearchParams = new URLSearchParams();
params.set('access_token', localStorage.getItem('access_token'));
return this.http.get('http://localhost:8080/user/selections', { search: params }).map((res: Response) => res.json());
These two services separately return two JSON Arrays. Then I need to do some login with these two arrays.
EDITED
service.ts
getUserInterests() {
return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());
}
getSavedSelections() {
let params: URLSearchParams = new URLSearchParams();
params.set('access_token', localStorage.getItem('access_token'));
return this.http.get('http://localhost:8080/interest/user/selections', { search: params }).map((res: Response) => res.json());
}
getSelectionList() {
var obs = this.getUserInterests().flatMap(
(interests) => {
return Observable.forkJoin([
Observable.of(interests),
this.getSavedSelections()
]);
}
);
return obs;
}
Then I am using following in my other ts file to call the service.
export class InterestsComponent {
private interests;
private saved_interests;
constructor(private dataService: DataService) {
this.dataService.getSelectionList().subscribe(
(result) => {
var interests = result[0];
var selections = result[1];
}
);
}
}
But this give following error on console log.
ORIGINAL EXCEPTION: TypeError: this.dataService.getSelectionList is not a function
Any suggestions are appreciated.
You need to leverage the flatMap
operator to call one request after the previous one completed:
this.service.getUserInterests().flatMap(
(interests) => {
let params: URLSearchParams = new URLSearchParams();
params.set('access_token', localStorage.getItem('access_token'));
return this.http.get('http://localhost:8080/user/selections', {
search: params
}).map((res: Response) => res.json());
}
);
When subscribing to this data flow, you will only receive the result of the last request.
You could use the Observable.forkJoin
method to return both. Here is a sample:
var obs = this.service.getUserInterests().flatMap(
(interests) => {
return Observable.forkJoin([
Observable.of(interests),
this.service.getUserSelections()
]);
}
);
obs.subscribe(
(result) => {
var interests = result[0];
var selections = result[1];
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With