chris01
chris01

Reputation: 12311

Angular/RxJS: synchronous observable

I have a service that has a method foo. Inside the method I subscribe to an observable (http-client).

foo () : boolean
{
  let ret : false;

  this.http.get ("/blabla").subscribe (
  (resp) =>
  {
    ret = true;
  }

  return ret;
);

I like to return a boolean value from foo() that depends on the get. That is not working because http.get is asynchronous - return is called before http.get finished.

How can I make this synchronous?

Returning the observable instead boolean is not an option here. That is because I handle the response of get in foo (not shown here) but I also need to act out of foo depending on its return.


I extended my sample with pipe and tap. Now I return the http.get-observable for outside the service and I process the http.get-result with tap.

foo () : Observable <any>
{
  return this.http.get ("/blabla").pipe (tap (x => handlehere ()));
}

As far I see, there is only one ugliness with it. I have the complexity of parsing the get-result inside AND outside of foo. I would prefer a simple boolean outside of foo.

Upvotes: 24

Views: 75950

Answers (1)

xrobert35
xrobert35

Reputation: 2556

This method can only run asynchronously, so you don't have a lot of option. Returning the observable and subscribe or return a promise. Perhaps returning a Promise will suit more your need in terms of comprehension.

In your service, the foo() method:

async foo() {
   const result = await this.http.get("/blabla").toPromise();
   
   // do what you want with result 

   return result;
}

How to call it:

this.myService.foo().then( (result) => {
   // Do what you want with the result
});

Upvotes: 27

Related Questions