aq2dwe
aq2dwe

Reputation: 45

How to pass subscribed data as input to other function?

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

Upvotes: 1

Views: 899

Answers (2)

Sushil Aggarwal
Sushil Aggarwal

Reputation: 1

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

Upvotes: 0

Sarthak Aggarwal
Sarthak Aggarwal

Reputation: 2312

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

Upvotes: 1

Related Questions