为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

杨__羊羊 2019-09-03 17:17:57
在我的Angular 2应用程序中,我有后端服务,如下所示。getUserInterests() {    return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());}在调用此服务后,我想在上一个服务成功之前调用另一个服务。第二次服务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());这两个服务分别返回两个JSON数组。然后我需要用这两个数组进行一些登录。EDITEDservice.tsgetUserInterests() {    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;}然后我在我的其他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];        }    );  }}但这会在控制台日志中出现以下错误。ORIGINAL EXCEPTION: TypeError: this.dataService.getSelectionList is not a function任何建议表示赞赏。
查看完整描述

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

您需要利用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());

  }

);

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


您可以使用该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];

  }

);


查看完整回答
反对 回复 2019-09-03
  • 1 回答
  • 0 关注
  • 521 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信