Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {}
}
like image 890
Get Off My Lawn Avatar asked Sep 12 '25 23:09

Get Off My Lawn


1 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.

like image 73
StepUp Avatar answered Sep 14 '25 12:09

StepUp