Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4 Migration : What are the Angular equivalent of Ionic 3 lifecycle events/nav guards?

I am having a tough time doing Ionic 3 to 4 migration. The Official migration guide asks us to use "the proper Angular alternatives". Can anyone tell me the equivalent Angular lifecycle-hooks replacements for the following Ionic 3 lifecycle-hooks.

  1. ionViewDidLoad
  2. ionViewWillEnter [not replaced]
  3. ionViewDidEnter [not replaced]
  4. ionViewWillLeave [not replaced]
  5. ionViewDidLeave [not replaced]
  6. ionViewWillUnload
  7. ionViewCanEnter
  8. ionViewCanLeave

Please help me match the above with

  1. ngOnChanges()
  2. ngOnInit()
  3. ngDoCheck()
  4. ngAfterContentInit()
  5. ngAfterContentChecked()
  6. ngAfterViewInit()
  7. ngAfterViewChecked()
  8. ngOnDestroy()

Edit : I have indeed gone through Ionic 4 router-outlet docs.

like image 345
Sebin Benjamin Avatar asked Jan 24 '19 09:01

Sebin Benjamin


2 Answers

ionViewDidLoad => ngOnInit()

ionViewWillUnload => ngOnDestroy()

From Angular Docs :

ngOnInit()
Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

ngOnDestroy()

Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks.

For ionViewCanEnter() and ionViewCanLeave() you have to use Router Guards as suggested in the docs. For eg. If you want to guard a route against an unauthenticated user you have to first create service file to check for authentication

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (isAuthenticated) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login']);
    return false;
}
}

and then in your route path use the service in canActivate property:

{path:'home',component:HomeComponent,canActivate:[AuthGuard]}
like image 128
ad999 Avatar answered Sep 23 '22 03:09

ad999


  1. ionViewDidLoad replaced by ngOnInit
  2. ionViewWillEnter [not replaced]
  3. ionViewDidEnter [not replaced]
  4. ionViewWillLeave [not replaced]
  5. ionViewDidLeave [not replaced]
  6. ionViewWillUnload replaced by ngOnDestroy
  7. ionViewCanEnter replaced by CanActivate
  8. ionViewCanLeave replaced by CanDeactivate
like image 20
MuturiAlex Avatar answered Sep 21 '22 03:09

MuturiAlex