如何在 ionic 2 中调用内置于 Angular 2 中的函数?

How do you call a function built in Angular 2 in ionic 2?

我正在尝试调用我在 ionic 2 选项卡中的 typescript/Angular 2 中编写的函数。我对打字稿很陌生,所以不完全知道它是如何工作的。

当我尝试调用函数时,控制台报错说我写的 randomise() 函数不是函数...

This is a JSFiddle file 我放代码的地方。 'cards' 部分工作完美,它只涉及我的随机函数。 HTML:

<button fab class="card-subtitle">{{randomise(100,10000) | currency :'USD' : true}}</button>

TS:

export class randomNumber {

    public number: number;

    constructor (min: number, max: number){
        this.randomise(min, max)
    }  
    randomise(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    }

}

就像@misha130 说的那样,您会收到该错误,因为 randomise(...) 方法不是您尝试调用它的同一组件的一部分。

我会稍微改变一下你的 class,像这样:

export class RandomNumber {

    constructor (){ }

    public randomise(min, max): number {
        return Math.floor(Math.random() * (max - min)) + min;
    }
}

您可以直接从实例调用它,而不是在构造函数中调用 randomise 方法,就像我们接下来要看到的那样。

您可以在 html 代码中执行类似的操作:

<button fab class="card-subtitle">{{getRandomNumber(100,10000) | currency :'USD' : true}}</button>

然后在您的组件中,包括一个从 RandomNumber class

的实例调用 randomise 方法的方法
// your page component

// Variable to hold the instance of the randomNumber class  
randomNumberInstance: any;
result: number;

constructor(){
    // your code...
    this.randomNumberInstance = new RandomNumber();
}

public getRandomNumber(value1: number, value2: number):number {
    this.result = this.randomNumberInstance.randomise(value1, value2);
}