Wie Sie sich here, @mhartington (von ionischen Team) sagt:
Just to chime in on this, you shouldn't be injecting ViewController or NavController into Service. This is not their intended purpose.
Und
Dass gesagt wird, können Sie das nav erhalten durch
var nav = this.app.getActiveNav();
tun Wie Sie here sehen können.
============================================== ===
EDIT: als ein anderer Benutzer sagte:
It's bad practice to change a view from a service (broken MVC). However, you could send events from services to the main controller, and the controller can use NavController (best way), or you could send NavController to your service like an attribute (not bad way...). Or you may need to create a component instead of using the service.
Also, einen besseren Weg, es zu tun, wäre:
zuerst ein observable
in Ihrem Dienst hinzuzufügen, zu wissen, wenn der dismiss
aufgerufen werden sollte:
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);
}
}
Und dann nur, in Ihrem app.ts
(oder in Ihrem meisten Top-Komponente):
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);
});
});
}
Denken Sie daran, es in der ionicBootstrap
Ihrer Anwendung hinzuzufügen:
ionicBootstrap(MyApp, [MyCustomService, ...], {
//statusbarPadding: true
});
Oder folgen Sie der Angular2 Style Guide, fügen Sie es als provider
in der obersten Komponente (MyApp in diesem Fall):
@Component({
templateUrl: 'build/app.html',
directives: [...],
providers: [MyCustomService]
})
class MyApp {
// ...
}
Oder (je nach Szenario/Service-Nutzung) übergeben Sie die Seite nav als Parameter an den Dienst –
Das ist feine Antwort, ich gehe in diesem Fall für die klassische Zusammensetzung. – MyFantasy512
Mhh irgendwelche Ideen, was das sein könnte? 'browser_adapter.js: 84 TypeError: Die Eigenschaft 'next' von 'null' kann in meinem Service Observable nicht gelesen werden. – nottinhill