5

Which of async/await or Observable should be used to call backend services on Angular?

Using async/await makes it easier to see the source code, so I would like to use async/await. In that case I think that it can be used with Observable#toPromise.

However, Angular's manual only shows examples using Obseravable, so should I use Observable?

myhr
  • 61
  • 1
  • 4
  • If I understand correctly: you want to know if you should return an Observable or a Promise from your http requests. Is that correct? (async/await is just one way to resolve promises). – dapperdan1985 Dec 06 '18 at 16:20
  • 2
    You should definitely learn Rx and use observables and forget about `.toPromise()`. It will allow you to express complex logic in a few lines of code. I know, it has a steep learning curve but it pays off after you get acquainted with them. – Bogdan Constantinescu Dec 06 '18 at 16:52
  • Why the downvote? This seems like a very legitimate question. Probably the answer is one of personal preference, coding stzle and guidelines, conventions and syntactic legibility... – masterxilo Apr 05 '19 at 12:29

2 Answers2

3

IMO observables are more difficult to handle than javascript promises, first because they don't have first-level support in the javascript syntax (there is no async/await and try/catch for them), and second you need to remember to unsubscribe.

I agree with the enhanced readability of the code with promises.

For cases where you expect exactly one event or one failure instead of many, a promise also makes more sense conceptually than an Observable stream of events.

masterxilo
  • 2,503
  • 1
  • 30
  • 35
0

As per the Angular documentation, you should use Observable.

Observables provide support for passing messages between publishers and subscribers in your application. Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values.

Source: https://angular.io/guide/observables

The second sentence from the quote above is key, specifically the mention of "other techniques", i.e., promises.

Additionally, it's not much harder to see the value (source code) of your http responses. In fact, the values are accessible once the Observable is subscribed to.

something.service.ts

...
public getSomething(): Observable<HttpResponse> {
    return this._http.get<HttpResponse>('/api/something');
}
...  

something.component.ts

...
public getSomethingMethod() {
    this._somethingService.getSomething()
        .subscribe((res: HttpResponse ) => {
            // Do something with res (values are now visible)
        })
}
...
dapperdan1985
  • 3,132
  • 2
  • 15
  • 26
  • What are the 'significant benefits' of using observables over other techniques? – pungggi Apr 09 '19 at 06:03
  • @pungggi personally, I can't speak from much comparison experience. The 'significant benefits' quote is from the angular team. Here's the first appealing search result from google that compares them. I found this article that may be helpful https://medium.com/@manuelalejandropm/advantages-of-observable-versus-promise-cbc0095995aa – dapperdan1985 Apr 09 '19 at 20:19
  • I'm coming from the async/await world right now, I still cannot see the benefits of using Observable to access the API data, like, for me a front-end Service to call the API does a call, returns a value, and that's it. Why should I botter subscribing if I could use a toPromise ? – Davi Daniel Siepmann Jan 25 '21 at 20:34
  • 1
    @pungggi: To be clear, I'm not the one claiming "significant benefits". It's quoted from the Angular documentation at the time of answering. I'm not sure I have a great answer of my own. Many people mention that Observables are cancellable out of the box and they do everything promises do and then some. If you're able to get by without them, promises are fine. On the other hand, it's hard to know if you would have benefited from using Observables until you've started using them and understand their capabilities. – dapperdan1985 Jan 26 '21 at 06:27
  • 2
    @DaviDanielSiepmann It's probably fine to use `toPromise` on most API responses, though you'll want to start using `lastValueFrom` since `toPromise` is deprecated. That said, if you decide you want to use RxJS operators later down the road, you'll have more refactoring to then if you continue using them as Observables and subscribing. Personally, I find Observables useful for retrying `503 Service Unavailable` in combination with a delay calculated from the `Retry-After` header using the `retryWhen` operator. – dapperdan1985 Jan 26 '21 at 07:23
  • 1
    those were pretty good points, in that case, I might suggest, if you're a beginner like me, simply start off using `.pipe(take(1))` to simplify your subscribe, and you'll get the benefits of using RXJS over time. Thank you @dapperdan1985 – Davi Daniel Siepmann Jan 26 '21 at 15:32