首页 > 解决方案 > 这个打字稿文件中的定义有什么问题

问题描述

我有一个对象数组,我想在评估表单的某些输入时使用它们。但是,在评估变量 this.ptp 时,我不断收到类型错误。谁能指出我正确的方向?

export class AppCadComponent implements OnInit {
  ptpForm: FormGroup;
  ptp: number = 0;
  ptp_list = [
    {"leeftijd":"30-39", ptp:0, "geslacht":"man", "score":1},
    {"leeftijd":"30-39", ptp:1, "geslacht":"vrouw", "score":2},
    {"leeftijd":"40-49", ptp:2, "geslacht":"man", "score":3},
    {"leeftijd":"40-49", ptp:3, "geslacht":"vrouw", "score":4},]

  answer: {};

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.ptpForm = this.fb.group ({
      ptp_age: [''],
      ptp_geslacht: [''],
    });
  }

  this.ptp = 1

  var antwoord = this.ptp_list.filter(function (item) {
    return item.leeftijd == formValue.ptp_age && item.geslacht ==formValue.ptp_geslacht && item.ptp == this.ptp
  });
  alert (answer.score);
}

标签: arraysangulartypescript

解决方案


您只能在类方法/构造函数内或在一般定义期间分配 this.ptp。

您可以在构造函数或 ngOnInit 中执行此操作

  constructor(private fb: FormBuilder) { 
     this.ptp = 1;
  }

或者

ngOnInit() {
    this.ptp = 1;
}

推荐阅读