Ionic2,将 NavController 注入 Injectable Service

Ionic2, inject NavController to Injectable Service

我在使用 Ionic2 框架的 Angular2 中使用可注入服务时遇到问题。

我的服务是这样的:

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。这很奇怪,因为在 任何页面 class 它都在工作,尽管它有 @Component,也许这就是问题所在。

编辑#1:

我在 ionicBootstrap 提供此服务,如下所示:

ionicBootstrap(MyApp, [ViewStackController], {});

如你所见here,@mhartington(来自 ionic 团队)说:

Just to chime in on this, you shouldn't be injecting ViewController or NavController into Service. This is not their intended purpose.

The service shouldn't be responsible for displaying alerts/loading/ or any component that needs to be activated by nav. A service should just be for getting and returning data.

Anything else should be done within the component.

也就是说,您可以通过以下方式获得导航

var nav = this.app.getActiveNav();

如你所见here

============================================= ====

编辑: 正如另一位用户所说:

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.

所以,更好的方法是:

首先,在您的服务中添加一个 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 Style Guide 之后,将其作为 provider 添加到最顶层的组件(本例中为 MyApp):

@Component({
  templateUrl: 'build/app.html',
  directives: [...],
  providers: [MyCustomService]
})
class MyApp {
  // ...
}