正如你在这里看到的,@mhartington(来自 ionic 团队)说:
只是为了解决这个问题,您不应该将 ViewController 或 NavController 注入到 Service 中。这不是他们的预期目的。
和
该服务不应该负责显示警报/加载/或任何需要由导航激活的组件。服务应该只是用于获取和返回数据。
其他任何事情都应该在组件内完成。
话虽如此,您可以通过以下方式获得导航
var nav = this.app.getActiveNav();
就像你在这里看到的一样。
=================================================
编辑:正如另一位用户所说:
从服务更改视图是不好的做法(损坏的 MVC)。但是,您可以将事件从服务发送到主控制器,并且控制器可以使用 NavController(最好的方式),或者您可以将 NavController 像属性一样发送到您的服务(不错的方式......)。或者您可能需要创建一个组件而不是使用该服务。
因此,更好的方法是:
首先,observable
在您的服务中添加一个,以了解dismiss
应该何时调用:
import {Injectable} from '@angular/core';
import {Platform} from 'ionic-angular';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class MyCustomService {
// Observables we're going to use
private dismissObserver: any;
public dismiss: any;
constructor(private platform: Platform){
// Your stuff
// ...
this.dismissObserver = null;
this.dismiss = Observable.create(observer => {
this.dismissObserver = observer;
});
}
public yourMethod(...):void {
// Here we send the order to go back to the home page
this.dismissObserver.next(true);
}
}
然后只有, 在您的app.ts
(或您最顶层的组件中):
initializeApp(): void {
this.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.styleDefault();
// We subscribe to the dismiss observable of the service
this.myCustomService.dismiss.subscribe((value) => {
this.navController.setRoot(HomePage);
});
});
}
请记住将其添加到ionicBootstrap
您的应用程序中:
ionicBootstrap(MyApp, [MyCustomService, ...], {
//statusbarPadding: true
});
或者,按照Angular2 样式指南,将其添加为provider
最顶层的组件(本例中为 MyApp):
@Component({
templateUrl: 'build/app.html',
directives: [...],
providers: [MyCustomService]
})
class MyApp {
// ...
}