cnak2
cnak2

Reputation: 1841

Can't add NavController to my app.component.ts

I'm tying to inject NavController into my app.component.ts, but I keep getting an error when running my app saying:

NullInjectorError: No provider for NavController!

I'm doing everything right as far as importing and declaring it, as I do with any other component I inject. But on my main app component it doesn't seem to like it.

What's going on there?

code:

import { AuthenticationProvider } from './../providers/authentication/authentication';
import {Component} from '@angular/core';
import { Events, Platform, NavController } from 'ionic-angular';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';
import {ScreenOrientation} from '@ionic-native/screen-orientation';




import {TabsPage} from '../pages/tabs/tabs';
import {LoginPage} from "../pages/login/login";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any = TabsPage;

  constructor(
    platform: Platform,
    statusBar: StatusBar,
    splashScreen: SplashScreen,
    events: Events,
    private navCtrl: NavController,
    private authProvider: AuthenticationProvider,
    screenOrientation: ScreenOrientation) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleLightContent();
      splashScreen.hide();

      //device-specific code, such as detecting screen rotation
      if (platform.is('cordova')) {
        screenOrientation.lock(screenOrientation.ORIENTATIONS.PORTRAIT);
      }

      events.subscribe('user:expired_token', () => {
        this.rootPage = LoginPage;
      });
    });
  }

  logout(){
    this.authProvider.logout();
    this.navCtrl.setRoot('LoginPage');
  }
}

Upvotes: 1

Views: 630

Answers (1)

Floyd
Floyd

Reputation: 367

You can reach your NavController in app.component.ts by:

<ion-nav #nav>
...

@ViewChild('nav')
public nav: NavController;

The reason is that NavController is not initialized yet when a root component is bootstrapping, so it can't be injected. See comment in source code

Upvotes: 3

Related Questions