As you can see in this source, @mhartington (from the ionic team) mentions:
It's not recommended to inject ViewController or NavController into a Service. They are not meant for that purpose.
Furthermore
A service should not handle displaying alerts, loading screens, or any components activated by navigation. Its main role is to fetch and return data.
Any other tasks should be handled within the component.
With that said, you can access the nav by using
var nav = this.app.getActiveNav();
As shown here.
=================================================
EDIT: Another user added:
Modifying a view from a service is not recommended as it breaks MVC. You could send events from services to the main controller instead, and have the controller handle NavController usage (preferred method). Alternatively, you could pass NavController to your service as an attribute (not ideal), or consider creating a component instead of using a service.
Therefore, a more suitable approach would be:
Start by adding an observable
in your service to determine when the dismiss
action should be triggered:
import {Injectable} from '@angular/core';
import {Platform} from 'ionic-angular';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class MyCustomService {
// Observables we're using
private dismissObserver: any;
public dismiss: any;
constructor(private platform: Platform){
// Your code here
// ...
this.dismissObserver = null;
this.dismiss = Observable.create(observer => {
this.dismissObserver = observer;
});
}
public yourMethod(...):void {
// Here we send the command to navigate back to the home page
this.dismissObserver.next(true);
}
}
Then only in your app.ts
(or top-most component):
initializeApp(): void {
this.platform.ready().then(() => {
// Platform is ready and plugins are available.
// Here you can perform any native actions.
StatusBar.styleDefault();
// Subscribe to the dismiss observable from the service
this.myCustomService.dismiss.subscribe((value) => {
this.navController.setRoot(HomePage);
});
});
}
Don't forget to include it in the ionicBootstrap
of your app:
ionicBootstrap(MyApp, [MyCustomService, ...], {
//statusbarPadding: true
});
Alternatively, as per the Angular2 Style Guide, add it as a provider
in the top-most component (MyApp in this case):
@Component({
templateUrl: 'build/app.html',
directives: [...],
providers: [MyCustomService]
})
class MyApp {
// ...
}