我想从一个类调用一个方法。我试过这个:
export class IdGenerator {
public randomString(): string {
const length = 40;
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = length; i > 0; --i) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
}我把它叫做这里:
import {IdGenerator} from '@utils/id.generator';
@Component({
selector: 'app-merchant-new',
templateUrl: './merchant-new.component.html',
styleUrls: ['./merchant-new.component.scss']
})
export class MerchantNewComponent extends FormBaseComponent {
formGroup = new FormGroup({
login: new FormControl(IdGenerator.randomString(), [Validators.required, Validators.maxLength(40)]),
});
constructor(private merchantService: MerchantService,
private router: Router) {
super();
}
}但是我得到了错误的TS2339: Property 'randomString' does not exist on type 'typeof IdGenerator'.
调用方法和获取字符串的正确方法是什么?
发布于 2019-02-18 22:01:31
您已经将randomString定义为实例方法。所以,你得把它叫做
new IdGenerator().randomString()如果要将其称为IdGenerator.randomString(),则应将此方法定义为静态的:
export class IdGenerator {
static randomString(): string {
...
}
}参见工作示例这里
https://stackoverflow.com/questions/54755968
复制相似问题