-2

I met with a lot of code with subscribe method in Angular, what will we lose if we do not use them?

Why all codes that uses subscribe, is being written in constructor instead of ngOnInit?

constructor(private router: Router) {
  m_Router.events.filter(event => event instanceof XComponent)
    .subscribe(e => {
      ...
    });
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
ozziem
  • 155
  • 3
  • 12

2 Answers2

0

Most features of Angular are based on observables allowing for asynchronously code execution. If you do not subscribe on a property like m_Router.events it will never return any value. Since an observable requires something to subscribe onto it.

Normally I would suggest placing all logic that needs to happen when a component loads in the ngOnInit method. Since the constructor is normally used for stuff like dependency injection. This post explains the it in more detail: Difference between Constructor and ngOnInit

An other note on subscribers and subscription is that you should manually unsubscribe from them when the component unloads. Angular takes care of this when using the HttpClient but for other subscription like the m_Router.events you should use the ngOnDestroy to unsubscribe. In order to do this you should store the subscriber in a variable when you subscribe to it.

Ruben
  • 58
  • 6
  • If so why everycode I met that includes subscribe clause take place in constructor? – ozziem May 24 '19 at 16:32
  • I'm not sure at which code you have been looking. Here is two articles which show you how to router based events or form based events. In both articles the subscription is done within the `ngOnInit`. Articles: https://alligator.io/angular/reactive-forms-valuechanges/ https://ultimatecourses.com/blog/dynamic-page-titles-angular-2-router-events – Ruben May 25 '19 at 12:26
0

The best practice for subscribing to services is in ngOnInit() lifeCycle hook method,

you can read this in the official documentation about angular services: example getHeroes service:

Tutorial about services

Call it in ngOnInit While you could call getHeroes() in the constructor, that's not the best practice.

Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn't do anything. It certainly shouldn't call a function that makes HTTP requests to a remote server as a real data service would.

Instead, call getHeroes() inside the ngOnInit lifecycle hook and let Angular call ngOnInit at an appropriate time after constructing a HeroesComponent instance.

ngOnInit() {
  this.getHeroes();
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93