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(); } }