How to use NavController from a Service in Ionic 3

ux-787980_640

Sometimes you want put some navigation code in a service. If the service is provided at root level you can’t inject the NavController because you don’t have any at application startup and your application will crash.

The naive solution is to pass the NavController as parameter to the service method like this:

@Injectable()
export class TestService {
  actionWithNavigation(navCtrl: NavController) {
    navCtrl.push(...);
  }
}

// And then in the page
class SamplePage {
  constructor(
    private service: TestService, 
    private navCtrl: NavController){
  }

  onClick() {
    this.service.actionWithNavigation(this.navCtrl);
  }
}

This solution is crap. What you can do instead is cheat a little bit and inject the App service into your service and get the current NavController from there:

import { App } from 'ionic-angular';

@Injectable()
export class TestService {
  constructor(private _app: App){
  }

  actionWithNavigation() {
    this._app.getActiveNav().push(...);
  }
}

// And then in the page
class SamplePage {
  constructor(private service: TestService){
  }

  onClick() {
    this.service.actionWithNavigation();
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s