I'm new to Angular. I have a service that needs to subscribe to a subject provided by another service. If this was a component, I would create the subscription in the ngOnInit method of the component. NgOnInit isn't called for Services, though. I have created an initialise method to create the subscription but I'm not sure where best to call it from. I have seen it done two ways:
1) Call the initialise method in the service constructor
2) Inject the service into the app.component and call the service initialise method in the app.component's ngOnInit method e.g.
method 1:
export class MyService{
constructor(private myRequiredService: RequiredService) {
this.initialiseSubs();
}
initaliseSubs(){
//code to set up subscriptions
}
}
Method 2
export class MyService{
constructor(private myRequiredService: RequiredService) {}
initaliseSubs(){
//code to set up subscriptions
}
}
export class AppComponent implements OnInit{
title = 'my-app';
constructor(private myService:MyService){}
ngOnInit(){
this.myService.initialiseSubs();
}
}
Both methods seem to work but I would welcome advice as to which is preferable. Thanks in advance.