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?

OPV
  • 1
  • 26
  • 81
  • 156
  • 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

1

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
  • 31,266
  • 5
  • 51
  • 75
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,487
  • 2
  • 10
  • 29