首页 > 解决方案 > 在角度重新分配变量时获取空/未定义

问题描述

我有一个测试数组:test = null;

我创建了一个函数,我正在为测试数组重新分配值,但它说的是空数组/未定义数组

abcd(){
    this.dataService.getAirport().subscribe(
      (data) => {
        this.airportData = data.data.data.metaDataRows;
        this.countryData = data.data.data.metaDataFields[0].column;
         const airConNames = this.countryData.values;
         this.test = [];
         this.test.push({name:'Select a Country', id:'0'});
         //this.test = [{name:'Select a Country', id:'0'}];
         console.log(this.test);
         airConNames.forEach(function(entry) {
           //console.log(entry.name);
           //console.log(entry.country_id);
          this.test = [{name : entry.name, id : entry.country_id}];
         });
        console.log(this.test); // this is null
      },
      (error) => {
        this.dataService.handleServiceError(error.message, this.TAG);
      }
    );
      console.log(this.test); //this is null
 }

控制台显示空,

我哪里错了

标签: angulartypescript

解决方案


有两件事,在foreach循环内,您this.test每次都设置为一个新数组。您应该进行this.test.push()操作或使用其余参数this.test = [{ ... }, ...this.test];(取决于您是想将其余部分放在最后(unshift)还是放在开头(push)。

接下来,this上下文不是您所期望的,因为您使用的是airConNames.forEach(function(entry) { ... }). 尝试使用箭头函数语法airConNames.forEach((entry) => {

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

箭头函数表达式的语法比函数表达式短,并且没有自己的 this、arguments、super 或 new.target。

在 foreach 之后看不到为什么this.test为空,这很奇怪。尝试:

this.test = airConNames.map(entry => ({ name: entry.name, id: entry.country_id }));
this.test.unshift({ name: 'Select a Country', id:'0' });

推荐阅读