TingSter
ไทย
dev, ionic · JANUARY 2, 2019

Ionic 2-3 Nav Guards

Ionic 2-3 Nav Guards

Ionic

For those familiar with Angular 2 ~ 4, you’re likely already acquainted with Routing Guards. When switching over to Ionic 2–3, where we don’t use Routes but rather NavController for pushing or popping windows within an Ionic app, you might wonder if a similar feature exists. Good news—it does! In Ionic 2–3, this feature is known as Nav Guards.

Similar to Routing Guards, Ionic 2–3 offers the ionViewCanEnter and ionViewCanLeave methods, which allow you to control the navigation between different windows in your app.

ionViewCanEnter: boolean/Promise: Runs before the view can enter. This can be used as a sort of “guard” in authenticated views where you need to check permissions before the view can enter

ionViewCanLeave: boolean/Promise: Runs before the view can leave. This can be used as a sort of “guard” in authenticated views where you need to check permissions before the view can leave

ionViewCanEnter is called first, allowing you to perform any necessary actions before deciding whether to enter the page. On the other hand, ionViewCanLeave is called when you’re about to leave the current page, just before navigating to another page.

export class MyClass {
  constructor(public navCtrl: NavController) {}

  //When trying to leave the page will call
  //ionViewCanLeave()
  pushPage() {
    this.navCtrl.push(DetailPage).catch(() => console.log("Something cache!"));
  }

  isValid() {
    return validValue;
  }

  //Make a decision to stay or leave.
  ionViewCanLeave(): boolean {
    return this.isValid();
  }
}

From the example above, you can see that before we push to DetailPage or navigate away from the current page to DetailPage, ionViewCanLeave() is invoked. The isValid() function serves as a condition check before deciding to leave the current page. If the result is False, the .catch() block will be executed. Similarly, ionViewCanEnter is used to verify whether the conditions we’ve set are met before entering the page.

export class DetailPage() {
  constructor(public navCtrl: NavController) {}

  isValid() {
    return (validValue);
  }

  ionViewCanEnter(): boolean {
    return this.isValid();
  }
}

This is a brief overview of how Nav Guards work. Give it a try in your projects, or take a look at the documentation for Ionic 2–3 for more detailed information.

Tags: #dev#ionic
Share: