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

后端 未结 1 2013
盖世英雄少女心
盖世英雄少女心 2021-01-24 13:23

In my Angular 2 app I have backend service as below.

getUserInterests() {
    return this.http.get(\'http://localhost:8080/test/selections\').map((res: Response)         


        
相关标签:
1条回答
  • 2021-01-24 14:29

    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];
      }
    );
    
    0 讨论(0)
提交回复
热议问题