Ionic2 / Angular2:从组件到中央服务

时间:2016-07-12 00:20:39

标签: angular ionic2

这是我们每个组件中的一部分:

import { HomePage } from '../../home/home';
@Component({
..
    dismiss() {
       this.navController.setRoot(HomePage)
    }

如何从服务中执行此操作? (我们尝试过它并不起作用,请参阅:Angular2: Pass Component Page from Service to other Component does not work

1 个答案:

答案 0 :(得分:1)

你可以here,@ mhartington(来自离子团队)说:

  

只是为了说明这一点,你不应该注入ViewController或者   NavController进入服务。这不是他们的预期目的。

  

该服务不应负责显示警报/加载/或   任何需要通过nav激活的组件。服务应该是   获取和返回数据。

     

其他任何事情都应在组件内完成。

话虽这么说,你可以通过

获得NavController
var nav = this.app.getActiveNav();

就像你可以看到here

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

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

  

从服务更改视图(破坏的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 Style Guide之后,将其添加为最顶层组件中的provider(在本例中为MyApp):

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