1

getActiveId function will return me the ID, based on the ID retuned I need to make another HTTP call to fetch the data using the function getOpenIssues.

So in my component, I subscribed to these functions I could see the ID is returned by getActiveId.

I passed the ID to getOpenIssues function, it throws id is not defined.

After searching through net, it is not possible to access variables outside the subscribed method.

Is that case how Do i pass the ID to other function ?

Please help, I'm not able to proceed further.

Service.ts

getActiveId() {
  return this.http.get<any>(apiUrl);
}
getOpenIssues(id: string) {
  return this.http.get<any>(Url);
}

Component.ts

this.service.getActiveId()
.subscribe(response => this.id = response.id) // Returns ID 22407

this.service.getOpenIssues(this.id) // Should pass the ID 22407
.subscribe((response) => { })
aq2dwe
  • 45
  • 1
  • 1
  • 10
  • Use faltMap. [see this question](https://stackoverflow.com/questions/33471526/why-do-we-need-to-use-flatmap) – SMH Oct 25 '18 at 08:13

2 Answers2

1

In your .component.ts, since both the functions are asynchronous, your getOpenIssues gets called before completion of getActiveId.

Hence you can make following changes :

this.service.getActiveId()
.subscribe(response => {
  this.id = response.id;
  this.service.getOpenIssues(this.id).subscribe(issues=>console.log(issues));// Returns ID 22407
  }) 

You can also take a look at different map operators of RxJS

this.service.getActiveId()
    .concatMap((id)=>this.service.getOpenIssues(id))
    .subscribe(issues=>console.log(issues))
Sarthak Aggarwal
  • 2,284
  • 1
  • 8
  • 12
0

Components can have 2 methods getActiveId() and getOpenIssues(). Now we need to call getActiveId() which will call first service based on the service's response, call another method of same component (which will call another service if required).

getActiveId() {
this.service.getActiveId()
.subscribe(response => {
this.id = response.id;
this.getOpenIssues();
});
}

getOpenIssues() {
this.service.getOpenIssues(this.id)
.subscribe(issues=> //Your logic);
}`
  • NO, @Sushil, bette ruse switchMap or flatMap – Eliseo Oct 25 '18 at 08:39
  • since response of 1 service will be the input to another service, so we have to work in my way. if calls were independent then obviously we can use flatmap or switchmap as per case. – Sushil Aggarwal Oct 26 '18 at 14:45