0

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

当我试图调用该函数时,控制台给出一个错误,指出我编写的 randomise() 函数不是函数......

这是我放置代码的 JSFiddle 文件。“卡片”部分完美无缺,它只涉及我的随机功能。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;
    }

}
4

1 回答 1

0

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

我会稍微改变你的课程,如下所示:

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>

然后在您的组件中,包含一个从类randomise的实例调用该方法的方法RandomNumber

// 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);
}
于 2016-08-15T17:47:18.407 回答