首页 > 解决方案 > Angular 调用一个帖子并接听电话,然后在上一个 get 调用完成后再次发帖并接听电话

问题描述

我有电话后接电话,如下所示:

 sendMessage(value) {
  getMessages(value);
 }

  getMessages(value) {
   this.http.post('url').subscribe((response)=> {
      if(response) {
   this.http.get('url).subscribe((getresponse)=> {
      if(getresponse) {
      // get call completed.
      }
     });
    }
  });
  }

我需要先调用 post 然后在完成上一个 get 之后再调用 get 然后 post 然后再调用 get。当前,当用户连续发送消息时,可能两次 sendMessage() 方法被触发两次,但调用是像 post call 一样发生,post call 然后是 get call get call。相反,它应该是 post call,然后是 get call,然后是第二个消息 post,然后是 get call。

你能告诉我我们如何以角度实现这一目标吗?

标签: angularhttpclient

解决方案


不确定这是否是您所追求的,但您可以使用 concatMap 运算符并在一个订阅中按顺序执行两个订阅

getMessages(value) {
 const both = this.http.post('url')
  .pipe(
    concatMap(result => {
        // here you have result to use in get
        this.http.get('url')
    })
  )
  .subscribe(result2 => {
    // do some stuff
 });
}

推荐阅读