Limit Page Access And Redirect to Other Page

Hi,

I have some working auth jwt system with my Ionic 2 app, inside user information contains “isPremium” flag …

Then some page

A. Dashboard Page
B. Page for All User
C. Page only for Premium User

How to make non premium user to redirect/push/setRoot to page A, when he visit page C?

I’ ve try to add some condition inside my page C onPageLoaded() method, and now i’m able to protect page C,

onPageLoaded() {
    if (! this.auth.isPremium()) {
        this.nav.setRoot(PremiumPage);

        return;
    }

    // the rest of code
}

but i’ve got this error

Attempt to use a destroyed view: detectChanges

Any idea? or maybe i should restructuring my code?

Thanks

AFAIK, the error is because the component is killed before it is fully loaded, so change detection does not get torndown properly.

Here are the Angular 2 and Ionic 2 Lifecycle loading hooks in the order that they trigger.

// Removed the if (this.auth.isPremium())... conditional for brevity
  ionViewLoaded() {
    console.log('ionViewLoaded');
    // this.nav.setRoot(LoginPage); // Error!  
  }
  ngOnInit() {
    console.log('ngOnInit');
    // this.nav.setRoot(LoginPage); // Error! 
  }
  ngAfterContentInit() {
    console.log('ngAfterContentInit');
    // this.nav.setRoot(LoginPage); // Error! 
  }
  ngAfterViewInit() {
    console.log('ngAfterViewInit');
    this.nav.setRoot(LoginPage); // Works!
  }
  ionViewWillEnter() {
    console.log('ionViewWillEnter');
    // this.nav.setRoot(LoginPage);  // Works!
  }
  ionViewDidEnter() {
    console.log('ionViewDidEnter');
    // this.nav.setRoot(LoginPage);  // Works! But produces a flash of content
  }

For my project, I’m currently using ngAfterViewInit until routing is enabled at which point I’ll look into using a Router Outlet and @CanActivate().

4 Likes

Thanks @cklanac :smile:

Thanks!!!
@cklanac
:slight_smile:

Thanks man :slight_smile:

Sorry! But I tried all the Things It’s working but When I am Clicking on the another page it is redirecting me to the root page . Please help

I want to perform the exit app from the particular page

 platform.registerBackButtonAction(() => {
  //uncomment this and comment code below to to show toast and exit app
  // if (this.backButtonPressedOnceToExit) {
  //   this.platform.exitApp();
  // } else if (this.nav.canGoBack()) {
  //   this.nav.pop({});
  // } else {
  //   this.showToast();
  //   this.backButtonPressedOnceToExit = true;
  //   setTimeout(() => {

  //     this.backButtonPressedOnceToExit = false;
  //   },2000)
  // }
  if(navCtrl.canGoBack()){
    this.navCtrl.pop();
  }
  else
  {
      this.showAlert();
  }
});