1

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?

POV
  • 11,293
  • 34
  • 107
  • 201
  • subscribe in a service?? I don't know yours requeriments but in general the services must not subscribe, are the components who subscribe to services – Eliseo Feb 19 '20 at 09:19

2 Answers2

6

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

  });

}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

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
Doflamingo19
  • 1,591
  • 4
  • 12
  • 32