1

In Typescript/Angular 6 (2+), is it considered a good practice to have a base abstract http service from which derives all the application services? for example:

//import the angular Http ...etc

export abstract class MyBaseService{
  ...
  protected get<T>(url: string): Observable<T> {
      return this.http.get(...)
        .pipe(map(result => result.json() as T));
  }

  protected post<T>....
  ...
}

We basically define all the rest methods (GET, POST, PUT, .. etc)

And then we have every service extend the base one:

export class MyFirstService extends MyBaseService{
  ...
  public doWork(data: MyModel): Observable<string> {
    this.post<string>(`my url`, data);
  }
  ...
}
  • 1
    This is opinion based – marstato May 25 '18 at 15:59
2

I think inheritance would be the best approach when it's services. In Angular you are unable to inject an instance of a service via 'provider' into another service. Instead, all the services would share the same instance. This is usually fine; however, if you want your BaseService to do more, such as handle errors, check if the call was successful, then store the result so your service can grab, then inheritance is the only real option you have.

If for example you used dependency injection and had your base service store values and give them out and your services are bound to these results. Then what would happen is all services that bind to it will be updated.

So at this point if you had EventService and Messages Service both would update with the same values.

1

I would rather use Dependency Injection instead of inheritance. And here is why:

  1. Everytime you update your MyBaseService constructor (at some point in the future you might want to inject another service in it, like HttpLogger or AlertService to handle errors etc) you need to update all the classes that inherit from it (you need to update super() call and also inject these new dependencies into them as well, and these dependencies might be irrelevant to the child class).

  2. What if you want to extend some of your services from something else in the future, you can't, cause you've already extended it from MyBaseService.

  3. During debugging - it is easier to reason about a single class, as you can see all the methods in it, you can grasp the class easily, while if you have inheritance, you need to keep in mind the parent class behaviour/methods/props as well. So if inheritance does not provide something really beneficial, then DI seems like a better choice.

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.