Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Angular service call a child method in constructor

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) {}
}

Upvotes: 4

Views: 652

Answers (2)

Berk Kurkcuoglu
Berk Kurkcuoglu

Reputation: 1523

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.

Upvotes: 0

StepUp
StepUp

Reputation: 38094

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.

Upvotes: 3

Related Questions