typescript Ionic 2 / Angular 2 中的全局函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43164262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
global function in Ionic 2 / Angular 2
提问by limit
How can I setup a global function that can be accessed throughout all views?
如何设置可以在所有视图中访问的全局函数?
In app.component.ts I added a simple method
在 app.component.ts 我添加了一个简单的方法
openShare() {console.log("button clicked")}
and then in my nav I have
然后在我的导航中我有
<button ion-button right (click)="openShare()">
<ion-icon name="md-share"></ion-icon>
</button>
When I try to access this from any page I get the following.
当我尝试从任何页面访问它时,我得到以下信息。
self.context.openShare is not a function
It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.
但是,如果我将它直接放在构造函数中(例如 this.openShare(); ),它确实执行得很好,但是当使用 (click) 函数从任何页面调用时,它就不起作用。
Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.
app.component.ts 不是全局的吗?我以为这是我放置它的地方,但也许我遗漏了一些东西。
Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.
基本上它是导航上一个简单按钮的功能,我需要它是全局的,因为它在每个页面上都使用过。
Any help would be appreciated, still figuring Ionic 2 out.
任何帮助将不胜感激,仍在弄清楚 Ionic 2。
回答by Harish Kommuri
You can use Directive
.
您可以使用Directive
.
Try as follows.
尝试如下。
Put the following code in separate directive file. (social-sharing.directive.ts);
将以下代码放在单独的指令文件中。(social-sharing.directive.ts);
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[socialSharing]'
})
export class SocialSharing {
constructor() { }
@HostListener('click') onClick() {
// Your click functionality
}
}
Import it into app.module.ts
and than add to declarations
.
将其导入app.module.ts
并添加到declarations
.
In HTML, just add attribute
to any element which is the selector
in your directive file.
在 HTML 中,只需添加attribute
到selector
指令文件中的任何元素。
<button ion-button right socialSharing>
<ion-icon name="md-share"></ion-icon>
</button>
Additional Info:
附加信息:
Passing values from component to directive.
将值从组件传递到指令。
home.html
主页.html
<button ion-button right [socialSharing]="property">
<ion-icon name="md-share"></ion-icon>
</button>
home.component.ts
主页.component.ts
export class HomePage {
property: string = 'some url';
constructor() {}
}
social-sharing.directive.ts
social-sharing.directive.ts
Import Input
along with others from @angular/core
.
导入Input
连同他人@angular/core
。
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);
};
}
Using Element in Directive:
在指令中使用元素:
social-sharing.directive.ts
social-sharing.directive.ts
Import ElementRef
along with others from @angular/core
导入ElementRef
与其他一起从@angular/core
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);
};
}
回答by Sampath
You can easily do that using Providers
.When you need to use that functionality (or provider), you just need to inject
it into your related component.That is it.
您可以使用 轻松做到这一点Providers
。当您需要使用该功能(或提供程序)时,您只需要将inject
其放入您的相关组件中。就是这样。
Method 1:
方法一:
You can create a Provider using CLI.
您可以使用 CLI 创建提供程序。
> ionic g provider YourProvider
your-provider.ts
你的供应商.ts
import { Injectable } from '@angular/core';
@Injectable()
export class YourProvider {
constructor() {
}
openShare() {console.log("button clicked")}
}
app.module.ts
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 { }
your-view.ts
你的view.ts
import { YourProvider } from '../../providers/your-provider';
export class YourViewPage{
constructor(public yourProvider : YourProvider) {
}
openShare(){
this.yourProvider.openShare();
}
Method 2:Creat an abstract
base class.
方法二:创建abstract
基类。
my-base-class.ts
我的基类.ts
export abstract class MyBaseClass {
constructor() {
}
protected openShare():void {
console.log("button clicked");
}
}
my-view.ts
我的-view.ts
export class MyViewPage extends MyBaseClass {
constructor()
{
super();
}
openShare(){
super.openShare();
}
}
回答by sebaferreras
Just like @Sampath mentioned, one way would be to use a custom provider. But since you method is just a simple one, I think you can use Eventsinstead. It'd be like this:
就像@Sampath 提到的那样,一种方法是使用自定义提供程序。但是由于您的方法只是一个简单的方法,我认为您可以使用Events代替。它会是这样的:
In your app.component.ts
file, subscribe to the new event:
在您的app.component.ts
文件中,订阅新事件:
import { Events } from 'ionic-angular';
constructor(public events: Events, ...) {
// ...
events.subscribe('social:share', () => {
// your code...
console.log("button clicked");
});
}
And then in any other page, just publish the event to execute that logic:
然后在任何其他页面中,只需发布事件即可执行该逻辑:
function anotherPageMethod() {
this.events.publish('social:share');
}