Ionic 2 中的全局函数 / Angular 2

global function in Ionic 2 / Angular 2

如何设置可以在所有视图中访问的全局函数?

在app.component.ts中我添加了一个简单的方法

  openShare() {console.log("button clicked")} 

然后在我的导航栏中我有

  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>

当我尝试从任何页面访问它时,我得到以下信息。

self.context.openShare is not a function

但是,如果我将它直接放在构造函数中(例如 this.openShare(); ),它确实执行得很好,但是当使用 (click) 函数从任何页面调用时,它就不起作用了。

app.component.ts不是全局的吗?我以为这是我要放的地方,但也许我遗漏了什么。

基本上它是导航上一个简单按钮的功能,但我需要它是全局的,因为它在每个页面上都使用。

任何帮助将不胜感激,仍在研究 Ionic 2。

您可以使用 Providers 轻松做到这一点。当您需要使用该功能(或提供程序)时,您只需将其 inject 到您的相关 component.That 中即可。

方法一:

您可以使用 CLI 创建提供程序。

> ionic g provider YourProvider

你的-provider.ts

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

    @Injectable()
    export class YourProvider {

      constructor() {
      }

       openShare() {console.log("button clicked")} 
    }

app.module.ts

import { YourProvider } from "../pages/path";

    @NgModule({
      declarations: [
        MyApp,
      ],
      imports: [
        IonicModule.forRoot(MyApp),
       ],
      bootstrap: [IonicApp],
      entryComponents: [
        MyApp,
        ],
      providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler },YourProvider  ]
    })

    export class AppModule { }

你的-view.ts

       import { YourProvider } from '../../providers/your-provider';

        export class YourViewPage{

          constructor(public yourProvider : YourProvider) {

          }

        openShare(){
           this.yourProvider.openShare(); 
        }

方法 2: 创建一个 abstract 基础 class。

我的基地-class.ts

export abstract class MyBaseClass {

  constructor() {
  }

  protected openShare():void {
    console.log("button clicked"); 
  }

}

我的-view.ts

export class MyViewPage extends MyBaseClass {
  constructor()
  {
     super();
  }

       openShare(){
               super.openShare(); 
            }
  }

就像提到的@Sampath 一样,一种方法是使用自定义提供程序。但是由于您的方法只是一个简单的方法,我认为您可以改用 Events 。应该是这样的:

在您的 app.component.ts 文件中,订阅新活动:

import { Events } from 'ionic-angular';

constructor(public events: Events, ...) {

  // ...

  events.subscribe('social:share', () => {

    // your code...
    console.log("button clicked");

  });

}

然后在任何其他页面中,只需发布​​事件即可执行该逻辑:

function anotherPageMethod() {
  this.events.publish('social:share');
}

你可以使用Directive.

尝试如下。

将以下代码放在单独的指令文件中。 (社会-sharing.directive.ts);

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[socialSharing]'
})
export class SocialSharing {

  constructor() { }

  @HostListener('click') onClick() {
    // Your click functionality
  }
}

将其导入 app.module.ts,然后添加到 declarations

在 HTML 中,只需将 attribute 添加到指令文件中 selector 的任何元素即可。

<button ion-button right socialSharing>
 <ion-icon name="md-share"></ion-icon>
</button>

附加信息:

从组件向指令传递值。

home.html

  <button ion-button right [socialSharing]="property">
    <ion-icon name="md-share"></ion-icon>
  </button>

home.component.ts

 export class HomePage {

   property: string = 'some url';
    constructor() {}
 }

社交-sharing.directive.ts

@angular/core.

中导入 Input 和其他内容
import { Directive, Input, HostListener } from '@angular/core';

@Directive({
   selector: '[socialSharing]'
})

export class SocialSharing {
  @Input('socialSharing') str: string;

  constructor() {}

  @HostListener('click') onClick() {
     console.log(this.str);
  }
};

  ngAfterInit() {
     console.log(this.str);
  };
}

在指令中使用元素:

社交-sharing.directive.ts

@angular/core

中导入 ElementRef 和其他内容
 import { Directive, ElementRef, HostListener } from '@angular/core';

 @Directive({
   selector: '[socialSharing]'
 })

 export class SocialSharing {

   // Add ElementRef to constructor

   constructor(el: ElementRef) {};

   ngOnInit() {
      let elRef = this.el.nativeElement;
      console.log(elRef.innerHTML);        
   };
 }