Warm tip: This article is reproduced from stackoverflow.com, please click
angular angular6

How to use subscribed data in another request in Angular

发布于 2020-03-27 10:23:42

I have post request which will submit the data. Once the data is submitted, I get the response where it contains ID of the item submitted.

That ID I have assigned it to a variable.

Now, I need to use that variable in another post request.

When I'm trying , I can see value is blank

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

Now I need to use lastItemCreatedId in another request

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

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

Info : Above two are post requests

How can I use lastItemCreatedID variable value in another post request ?

Questioner
Shivaay
Viewed
121
wentjun 2019-07-03 22:53

Since both methods are called one after another, you should use RxJS's mergeMap operator.

We can use mergeMap to map over the observables from the createItem() into an inner observable, which will subsequently assigned as part of the url variable. Then, we call the addAttachementstoItem() method, and the observables are returned in subscribe() on the subsequent line.

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
    })