2
\$\begingroup\$

What is the problem when I return a promise from angular service instead of Observable? If it's a matter of any manipulation or side-effect, that I can easily do inside angular service itself. Then why I shouldn't return a promise over observable?

Here's my code for service class

public async getCountriesAsync(filter: PaginateFilter): Promise<Paginate<IdNameTypeModel>> {
return await this.http.get<Paginate<IdNameTypeModel>>(`/api/{version}/Types/{lang}/Countries${filter.url()}`)
  .pipe(map(response => {
    return response == null ? new Paginate<IdNameTypeModel>() : response;
  })).toPromise();   
}

Using inside component

async loadCountries() {
  const filter = new PaginateFilter(this.data.pageIndex, this.data.pageSize);
  this.countries = await this.dldTypesService.getCountriesAsync(filter);
}
\$\endgroup\$
1
  • \$\begingroup\$ On a side note, always use triple equality -> response == null will be true if response = undefined as well. \$\endgroup\$ – Christian Ulbrich Jan 12 '20 at 23:24
1
\$\begingroup\$

Per se returning a promise from an Angular Service is not bad, however there are numerous things in Angular world that are heavily based on Observables:

  • usually you will likely change the change detection to ChangeDetectionStrategy.OnPush in your components and this will most likely be easier with Angular's async pipe not a problem, because async also supports Promises.
  • if you use your services for any kind of state and if your are using NgRx for effectively managing it, you'll be using @Effectsthat are basically a lot of RxJs magic and thus it might be easier to use Observables in the first place.
  • composing services for Guards is easier with Observables

Having that said, I agree with you, that typical REST services are fire and forget and thus IMO do not fit really into Observables well which are meant to be constant sources of events.

It is all about composition, Observables allow better composition for multiple async operations that need to be composed, whereas Promises can be nowadays used pretty easy with async/await for singular, isolated operations.

In the end, I'd advise to stick with the same convention throughout your whole app - either have all services return Promises and convert them to Observables when needed or always use Observables. I assume a lot of examples are using Observables because for non-trivial apps you end up needing better composition options than with pure Promises.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.