javascript - Angular 2: Two backend service calls on success of first service -


in angular 2 app have backend service below.

getuserinterests() {     return this.http.get('http://localhost:8080/test/selections').map((res: response) => res.json()); } 

after calling service want call 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 2 services separately return 2 json arrays. need login these 2 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 using following in other ts file call 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 give following error on console log.

original exception: typeerror: this.dataservice.getselectionlist not function 

any suggestions appreciated.

you need leverage flatmap operator call 1 request after previous 1 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 data flow, receive result of last request.

you use observable.forkjoin method return both. here 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];   } ); 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -