Search code examples
angularionic-frameworklifecyclesubscription

Difference between ionic and angular and ionic lifecycles


I have a page that shows cities: this page use a provider called "CitiesProvider" Since these cities can change, i put u Subscription like:

this.citiesSubscription = this.CitiesProvider.salesChanged
  .subscribe(
    (cities: City[]) => this.cities = cities
  )

Where is the perfect place to put the "unsubscribe" method between: ionViewWillLeave

or ionViewDidLeave

or ionViewWillUnload and what will go wrong if i put it in another?

And what's the difference between using these (Ionic) lifecycle hocks or using

ngOndestroy from Anglar or any hocks coming from angular (since the ionic pages are also angular component


Solution

  • You should use ngOnDestroy or ionViewWillUnload to unsubscribe from Observables.

    The ionViewDidLeave and ionViewWillLeave hooks are getting fired every time you leave a page but don't indicate a page getting destroyed /removed from the dom.

    Example:

    If you use the NavController to push a page onto the stack the ionViewDidLeave but not the destroy hook is triggered because the page actually stays in the dom. If you navigate back the subscriptions are still assuring everything is up to date.

    If you would unsubscribe while leaving the page you need to subscribe again in the ionViewWillEnter lifecycle hook.