Angular 2:两个后端服务调用第一个服务成功

Ros*_*e18 15 javascript angular-services angular

在我的Angular 2应用程序中,我有后端服务,如下所示.

getUserInterests() {
    return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());
}
Run Code Online (Sandbox Code Playgroud)

在调用此服务后,我想在上一个服务成功之前调用另一个服务.

第二次服务

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());
Run Code Online (Sandbox Code Playgroud)

这两个服务分别返回两个JSON数组.然后我需要用这两个数组进行一些登录.

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;
}
Run Code Online (Sandbox Code Playgroud)

然后我在我的其他ts文件中使用以下来调用该服务.

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];
        }
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但这会在控制台日志中出现以下错误.

ORIGINAL EXCEPTION: TypeError: this.dataService.getSelectionList is not a function
Run Code Online (Sandbox Code Playgroud)

任何建议表示赞赏.

Thi*_*ier 18

您需要利用flatMap运算符在上一个请求完成后调用一个请求:

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());
  }
);
Run Code Online (Sandbox Code Playgroud)

订阅此数据流时,您只会收到上一个请求的结果.

您可以使用该Observable.forkJoin方法返回两者.这是一个示例:

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];
  }
);
Run Code Online (Sandbox Code Playgroud)