温馨提示:本文翻译自stackoverflow.com,查看原文请点击:angular6 - How to use subscribed data in another request in Angular
angular angular6

angular6 - 如何在Angular的另一个请求中使用订阅的数据

发布于 2020-03-27 11:17:16

我有发布请求,将提交数据。提交数据后,我将收到包含已提交项目ID的响应。

该ID我已将其分配给变量。

现在,我需要在另一个发布请求中使用该变量。

当我尝试时,我看到值是空白

 this.sharepointService.createItem().subscribe( (response : Response) => {
      this.lastItemCreatedId = response['d'].ID;  // latitemcreated is a variable
      console.log("Newly created Item ID :" + this.lastItemCreatedId)
    })

现在我需要在另一个请求中使用lastItemCreatedId

      let url = "_spPageContextInfo.webAbsoluteUrl"+"_api/web/lists/getByTitle('List')/items('"+this.lastItemCreatedId+"')/AttachmentFiles/add(FileName='abc.txt')"

 this.sharepointService.addAttachementstoItem(url).subscribe()

信息:以上两个是发帖请求

如何在另一个发布请求中使用lastItemCreatedID变量值?

查看更多

查看更多

提问者
Shivaay
被浏览
223
wentjun 2019-07-03 22:53

由于这两种方法都一个接一个地调用,因此应使用RxJS的mergeMap运算符。

我们可以用来mergeMap将可观察变量从映射createItem()到内部可观察url变量,然后将其作为变量的一部分进行分配然后,我们调用addAttachementstoItem()方法,并在下一行的subscription()中返回可观察值。

import { mergeMap } from 'rxjs/operators';

this.sharepointService.createItem()
  .pipe(
    mergeMap((response : Response) => {
      this.lastItemCreatedId = response['d'].ID;
      let url = "_spPageContextInfo.webAbsoluteUrl"+"_api/web/lists/getByTitle('List')/items('"+this.lastItemCreatedId+"')/AttachmentFiles/add(FileName='abc.txt')"
      return this.sharepointService.addAttachementstoItem(url);
    }).subscribe(res => {
      // do the rest here
    })