从类调用方法

时间:2019-02-18 21:56:29

标签: angular typescript angular6

我想从一个类中调用一个方法。我尝试过:

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'.

调用方法并获取String的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您已将randomString定义为实例方法。因此,您必须将其称为

new IdGenerator().randomString()

如果您想将其命名为IdGenerator.randomString(),则应将此方法定义为静态方法:

export class IdGenerator {

  static randomString(): string {
    ...
  }
}

请参阅工作示例here