-1

基金-dropdown.js

export class FundDropdown{
  fundTypes: string[];
  fundCategorys: string[];
}

测试组件.ts

 export class PrimengTestComponent implements OnInit {
  date: Date;
  fundDropdown: FundDropdown;

  constructor(private fundInfoService: FundInfoService) {
    console.log(this.fundDropdown);
    console.log(this.fundDropdown.fundTypes.length);//the error occurs in this line
 }
 ngOnInit(): void {
    this.fundDropdown = new FundDropdown();
    this.fundInfoService.getFundTypeAndFundCategory().subscribe(
      (data) => {
        console.log(data);
        this.fundDropdown = data;
      },
      (error) => console.log(error)
    );
  }
}

fundDropdown 的数据是:

{"fundCategorys":["aaaa"],"fundTypes":["sdf","qwe","agas"]}

FundDropdown 数据来自后台,其类型为 Map<String, List>

4

2 回答 2

0

因为fundDropdown在这里是未定义的,所以到目前为止没有fundTypesonfundDropdown的值。

您必须声明如下类型的空对象FundDropdown

fundDropdown = <FundDropdown>{};

通过这样做,您可以访问 -

this.fundDropdown.fundTypes

仍然,您不能在其上使用length属性,因为数组fundTypes尚未声明为空数组。

所以你应该把这个控制台放在方法中this.fundInfoService.getFundTypeAndFundCategory().subscribe(...,因为数据是动态的。

于 2020-06-24T07:28:50.637 回答
0

在构造函数fundDropdown中未定义。

正如您所提到的,数据来自后端,您不知道它何时会到达,但在响应之前fundDropdown将是未定义的。

另一方面,constructor将首先被触发,因此不可能更快地从 接收数据ngOnInit。如果您搜索 Angular 生命周期,您可以了解更多关于它们的信息。

角生命周期

于 2020-06-24T07:35:04.190 回答