0

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?

  • Instead of a service that was tied to a specific entity like a Hero, what if the service really was a true service, like Banker, e.g.. Banker.GetBalance(accountNumber)? – Robert Harvey Mar 20 '17 at 16:23
  • 5
    On another note, why should a Hero object require the knowledge to save itself? See deviq.com/persistence-ignorance – Robert Harvey Mar 20 '17 at 16:26
  • 1
    I may be worng but, looks like moongose implements en.m.wikipedia.org/wiki/Active_record_pattern. Checkout the section Criticism – Laiv Mar 20 '17 at 20:21
  • 1
    Thanks for the responses. If I am understanding correctly, this sounds more like a difference in design decision as opposed to any specific benefits or limitations from being a frontend framework? – Zsw Mar 21 '17 at 16:28
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.

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.