This.app is undefined

Hi,

I get the error: ERROR TypeError: “this.app is undefined” when I call the logout function.
I search around and I read something related the “undefined” errors but I don’t solve it.
I know that the getRootNav() is deprecated but still working.

Can you help me?

This my code:

import { Component } from '@angular/core';
import { NavController, App } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service/auth-service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  app: any;
  public userDetails: any;
  responseData: any;

  userPostData = {"user_id":"","token":""};

  constructor(public navCtrl: NavController, public authService:AuthService) {
    const data = JSON.parse(localStorage.getItem('userData'));
    this.userDetails = data.userData;

    this.userPostData.user_id = this.userDetails.user_id;
    this.userPostData.token = this.userDetails.token;

  }

  backToWelcome(){
    
    const root = this.app.getRootNav();
    root.popToRoot();
  }

  logout(){
    //Remove API token
    localStorage.clear();
    setTimeout(() => this.backToWelcome(), 1000);

  }

}

Where is the part where you actually assign anything to app?

Here, isn’t? I’m a beginner with ionic.

Well, I guess I don’t assign any… Where is supposed I must assign it?

You are creating your own app member variable, but you don’t assign anything to it as was pointed out. It seems what you are intending to do is inject App from ionic-angular into the class. Remove app: any; and inject App through the constructor instead:

constructor(private app: App, public navCtrl: NavController, public authService:AuthService)

You should then be able to use this.app.

1 Like

Yes :slight_smile: Works like a charm!

Exist other way of do the same?

Not that you have any reason to care about my opinion, but injecting App is a red flag of bad design for me. It suggests action-at-a-distance.

Interesting. How then? I’m learning

If you’re specifically asking about user authentication, my approach looks like this.