1

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!

Alice
  • 15
  • 3
  • 1
    https://stackoverflow.com/questions/52485266/angular-rxjs-synchronous-observable I tried this toPromise() way, and it works! – Alice Nov 11 '21 at 05:43
  • You'd have to wait for your `GetResponseDataMethod` method to finish before open the dialog. As you realized yourself it's an asynchronous operation, meaning your next code line (ie opening the dialog) isn't going to wait for it. So you could either make your `GetResponseDataMethod` method return an `Observable` itself or you directly call your service, subscribe to it and only open dialog once a response has been received. Let me know if you need more details. – Aldin Bradaric Nov 11 '21 at 08:11

2 Answers2

0

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

Nadim
  • 43
  • 7
  • Thanks for the reply and help! I tried this way, but it won't wait for the API call finish. I think it related to synchronous call / pipe, subscribe.. but not sure how to do it..... – Alice Nov 11 '21 at 05:35
  • @Alice I am new to angular too but it usually work for me . Show this.service.getResponse(input) code too let us know how your http method is used. – Nadim Nov 11 '21 at 09:10
0

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
    }
  });
}
ruth
  • 29,535
  • 4
  • 30
  • 57