[英]Ionic2, inject NavController to Injectable Service
我使用Ionic2框架在Angular2中使用Injectable Service時遇到問題。
我的服務如下:
import {Injectable} from '@angular/core';
import {NavController} from 'ionic-angular';
@Injectable()
export class ViewStackController {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
}
}
我收到錯誤No provider for NavController
。 這很奇怪,因為在任何Page類中它都有效,雖然它有@Component
,也許這就是捕獲。
編輯#1:
我在ionicBootstrap
提供這項服務,如下所示:
ionicBootstrap(MyApp, [ViewStackController], {});
正如你可以在這里看到的那樣 ,@ mhartington(來自離子團隊)說:
只是為了說明這一點,你不應該將ViewController或NavController注入Service。 這不是他們的預期目的。
和
該服務不應負責顯示警報/加載/或需要由nav激活的任何組件。 服務應該只是用於獲取和返回數據。
其他任何事情都應在組件內完成。
話雖這么說,你可以通過做到獲得導航
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 {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.