Angular2:同步两个帖子请求

时间:2016-11-12 10:40:16

标签: javascript ajax post angular observable

我有两个ajax post请求,需要作为同步调用执行。 场景是表单创建了两种不同类型的对象,这些对象需要作为post请求发送到不同的API,我必须在UI上显示动画,直到两个API都将结果返回给UI。

任何帮助!

编辑以添加代码

  doApproveSingle() {
    //animation part
    this.loading = true
    //call 1
    this._http.post('api/single', this.approvedChanges, contentHeaders).subscribe(resp => { 
    }, error => {
    })
    //call 2
    this._http.post('api/new', this.approveNew, contentHeaders).subscribe(resp => {
    }, error => {
    })
  }

在两个调用完成后,我需要关闭该动画的两个帖子请求,需要该部分的帮助。

1 个答案:

答案 0 :(得分:1)

  doApproveSingle() {
    //animation part
    this.loading = true
    //call 1
    let obs1 = this._http.post('api/single', this.approvedChanges, contentHeaders)
    .map(resp => { ... });
    //call 2
    let obs2 = this._http.post('api/new', this.approveNew, contentHeaders)
    .map(resp => { ... });
    Observable.zip([obs1, obs2]).subscribe(val => this.loading = false);
  }

如果单个HTTP调用完成后无处可执行,则.map(...)部分可以省略。