Angular service call a child method in constructor

Viewed 85

Is there a way to call a child class method from an abstract service? When I do this, the if statement doesn't execute because onInit doesn't exist. I am not sure why it doesn't exist though. Maybe there is an "angular" way of doing this instead of triggering this on the init. Or maybe I just need to call the onInit manually in the component instead. Basically what I am doing is trying to get the initial application data from the server.

@Injectable({providedIn:'root'})
export class RootService {
  public constructor(httpClient: HttpClient) {
    if(typeof this.onInit === 'function') {
      this.onInit()
    }
  }
}
@Injectable({providedIn:'root'})
export class MyService extends RootService {
  public onInit() {
    // Do stuff
  }
}
@Component()
export MyComponent {
  public constructor(myService: MyService) {}
}
2 Answers

Services do not have lifecycle events. However, components have lifecycle hooks such as:

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ...

So you can load data when your component is initialized. If yes, then just use ngOnInit:

import { Component, OnInit } from '@angular/core';

@Component()
export MyComponent  implements OnInit {
    yourData;

    public constructor(myService: MyService) {}

    ngOnInit(){
        myService.loadData()
            .subscribe(s=> yourData = s);
    }
}

According to Angular docs:

OnInit is a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive.

If you add the service to the providers of your component, it will be in your components scope then you can call onInit in your service as well.

But the downside of this is you can no longer share the same instance of the service among your components.

This will be valid if your service only serves one component.

Related