When we use ngOnInit in services?
For exmaple I need to listen Observer inside service:
this.eventService.subscribe((data) => {
});
Where better place this code inside constructor or ngOnInit?
When we use ngOnInit in services?
For exmaple I need to listen Observer inside service:
this.eventService.subscribe((data) => {
});
Where better place this code inside constructor or ngOnInit?
ngOnInit
is a angular life cycle hook. They are only available within component/directives. In services, you can't use them.
So need to use this under the constructor.
constructor(){
this.eventService.subscribe((data) => {
});
}
You need to pust observer in ngOnInit
. the firrence is:
constructor
is used when the object is instantiated and you need it when you have some fields that must be initialitated.ngOnInit
is is a life cycle hook called by Angular when the component is created