Home > Software design >  How to retrieve API response data, then use it in the next method? RxJS
How to retrieve API response data, then use it in the next method? RxJS

Time:11-12

I have tried a while, but still could not figure out how to implement the following with RxJS.

Here is one click event : MainMethod()

In this MainMethod()

I first need to call API endpoint to get the Data : reponseData from GetResponseDataMethod()

GetResponseDataMethod(){
this.service.getResponse(input).subscribe(result => {return result.Data;})
}

this GetResponseDataMethod() is working fine. and I can get the data.

Then in the MainMethod() I need to get response from this GetResponseDataMethod() then Passing it to another child component. But It always open this component, then only go through this GetResponseDataMethod().

Basically I got undefined, for the API response data I need to use.

MainMethod(){
var responseData = GetResponseDataMethod();
this.dialog.open(ChildComponent, {data : {responseDataParameter: responseData}})
}

How can I implement this using RxJS, please help?

Thank you so much!

CodePudding user response:

Your end point method is not returning anything.

Global variable finalresult ; hold value in a variable then return that variable Like finalresult= result.Data; And return finalresult after your service.getResponse line end ;

Format code issue while replying from mobile so explaining you. Hope so it will work

CodePudding user response:

The async nature of the API request must be preserved. In other words, you'd need to subscribe to the observable where it's response is needed. Also you cannot return data from subscription callbacks.

MainMethod(){
  this.service.getResponse(input).subscribe({
    next: (result: any) => {
      this.dialog.open(ChildComponent, {data : {responseDataParameter: result.Data}});
    },
    error: (error: any) => {
      // handle errors
    }
  });
}
  • Related