In Angular 2's official tutorial, any operation involving getting or saving a class necessitates using a service. For a Hero
class, they had to create a HeroService
to perform all HTTP calls. This includes getting a single Hero
object with heroService.getHero
, and creating or updating a single Hero
object with heroService.create
or heroService.update
.
Contrast this with mongoose. Most of the operations to get or save a class in mongoose is performed via a method on object itself, as opposed to using a service. Mongoose's equivalent of heroService.getHero
would be Hero.findOne
. Instead of heroService.create
or heroService.update
, mongoose would have Hero.create
or hero.save
.
Granted, Angular 2 is an entire frontend framework, and mongoose is a backend library for mongodb specifically. So my question is, are there any specific benefits or limitations which necessitates that Angular 2 use a service for these operations, as opposed to simply performing HTTP calls via methods on the object itself? Or is this entirely a design choice, where either way could've worked equally well?
1 Answer 1
Because of abstraction of HTTP calls. In HeroService you can change context url to http calls without changing core part of application, or create HeroService mock, or re-implement it way you like (even for another protocol). HeroService is supposed to save hero and return. Rest of application (callers of HeroService) is NOT supposed to know HOW HeroService is doing it. It's implementation hiding. Hero should not save himself (how)? HeroService should be also stateless.
Explore related questions
See similar questions with these tags.
Hero
, what if the service really was a true service, likeBanker
, e.g..Banker.GetBalance(accountNumber)
?