Async/await or Observable in Angular

邮差的信 提交于 2021-01-24 07:16:27

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/53655441/async-await-or-observable-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!