No provider for NavController error in RC4


#1

Hi everyone,

I’m getting this error when try to add NavController to app.component.ts:

There is my code (simplified):

[...]
import {NavController, Platform, Config, AlertController} from 'ionic-angular';
[...]

@Component({
    template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {

    constructor(public navCtrl: NavController, [...]  ){

        platform.ready().then(() => {
        
            [...]

            if(platform.is('cordova')) {
                // subscribe to push notifications
                push.rx.notification().subscribe((push) => {
                    let alert = this.alertCtrl.create({
                        title: push.title,
                        subTitle: push.text,
                        buttons: [{
                            text: "OK",
                            handler: () => {
                                this.navCtrl.push(SomePage,{param: push.payload['player']});
                            }
                        }]
                    });
                    alert.present();

                });
            }

            [...]

        });

    }    

}

My system information:

Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.17
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 1.0.0
ios-deploy version: 1.9.0
ios-sim version: 5.0.11
OS: macOS Sierra
Node Version: v7.1.0
Xcode version: Xcode 8.2.1 Build version 8C1002

AlertController works fine, showing me the basic alert.

What I’m doing wrong?

Thanks.


#2

Solution found!

There are a section in the documentation called “Navigating from the Root component” where says:

What if you want to control navigation from your root app component? You can’t inject NavController because any components that are navigation controllers are children of the root component so they aren’t available to be injected.

By adding a reference variable to the ion-nav, you can use @ViewChild to get an instance of the Nav component, which is a navigation controller (it extends NavController):

import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
   template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
export class MyApp {
   @ViewChild('myNav') nav: NavController
   public rootPage = TabsPage;
   // Wait for the components in MyApp's template to be initialized
   // In this case, we are waiting for the Nav with reference variable of "#myNav"
   ngOnInit() {
      // Let's navigate from TabsPage to Page1
      this.nav.push(Page1);
   }
}

#3

Hi Ramon,

With this solution now you need to implement the @ViewChild on all pages that needs the Navigation instead the injection in the constructor?


#4

Hi @afernandez2000,

no, just in my app.component.ts.