我想在一个角度应用程序中使用JavaScript代码。我试过这个:
export class MerchantNewComponent extends FormBaseComponent {
constructor(private merchantService: MerchantService,
private router: Router) {
super();
}
function randomString() {
var length = 40;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
}但我知道这个错误:

有人知道我如何在一个角度应用程序中使用这个JavaScript代码吗?
发布于 2019-02-18 14:04:36
使用TypeScript语法在类中声明方法:
export class MerchantNewComponent extends FormBaseComponent {
getRandomStr(): string {
// ...
}
}备注
randomString变成了getRandomStr --这说明了函数到底是做什么的)有关更多信息,请访问TypeScript课堂手册
编辑:若要指定应传递给方法的参数,请参见下面:
getRandomStr(randomLength: number): string {
// Do something w/ the randomLength variable
console.log(randomLength);
// ...
}发布于 2019-02-18 13:54:48
应该是public randomString而不是function randomString
function可以在类之外使用,如果它在类内,那么它是类的方法,不再是函数了。
如果在组件中使用它,则可以在模板中使用this.randomString()或randomString()来调用它。
您也可以使用getter public get randomString() {...},然后当您使用它时,只需将其称为this.randomString。
https://stackoverflow.com/questions/54748797
复制相似问题