在离子2 angularjs 2的几个视图之间共享一个函数

Run*_*ter 0 typescript ionic2 ionic3 angular

关于我的应用程序与离子2和angularjs的几个视图我在每个页面上使用一些离子吐司消息.这些Toast消息对于每个页面都是相同的.

是否可以在可注入服务中定义这些消息,而不是在所有TS文件中创建相同的函数?

seb*_*ras 5

就像@Austin说的那样,你应该把你的逻辑放在injectable service:

import {Injectable} from "@angular/core";

@Injectable()
export class ToastService {
  constructor(...) {
      // ...
  }

  showToast() {
      //....
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将其包含在ionicBootstrap您的app.ts文件中,以确保在整个应用程序中使用相同的服务实例.

ionicBootstrap(MyApp, [ToastService], {});
Run Code Online (Sandbox Code Playgroud)

最后,您可以通过以下方式使用它component:

import {Component} from '@angular/core';
import {ToastService} from './toastService';

@Component({
  templateUrl: 'build/test.html'

})
export class TestPage {
  constructor(private toastService: ToastService) {
    // ...
  }

  showMessage() {  
      // Use the service to show the message
      this.toastService.showToast();
  }
}
Run Code Online (Sandbox Code Playgroud)