【问题标题】:Array is null when calling `.push`调用`.push`时数组为空
【发布时间】:2022-01-03 15:58:39
【问题描述】:

我正在开发一个 Angular 应用程序。在我的组件.ts 文件中,我有一个数组如下:

public myArray = [];
public dataFromAPI  = [];

每当我尝试在此数组中推送一个元素时,在我的一种方法中,它都会给我以下错误:

   this.appService.getData.subscribe(resp => {
      if (resp != null) {
          this.dataFromAPI = resp;
          this.dataFromAPI.forEach(element => {
            this.myArray.push(element)
          })
      }

RROR TypeError: Cannot read properties of null (reading 'push')

我的代码中没有发现任何错误。我总是像这样定义一个新数组,但我第一次遇到这个错误。如何解决?

【问题讨论】:

  • 您好,请问您可以将push 元素所在的代码添加到此特定数组吗?
  • @Roma,能否请您在 forEach 循环中创建 this 的 console.log,以检查 forEach 中 this 的值是什么

标签: javascript angular typescript angular9


【解决方案1】:

声明应如下所示

public myArray:any = [];
public dataFromAPI:any  = [];

你应该像下面这样直接循环api的响应(请检查响应对象内部可能有更多的键,通过键访问数组)

   this.appService.getData.subscribe(resp => {
      if (resp != null) {
          resp.data.forEach(element => {
            this.myArray.push(element)
          });
      this.dataFromAPI = resp;
      }
   }

【讨论】:

    【解决方案2】:

    我不确定public myArray = []; 是什么语法。下面将适用于打字稿。

    const myArray: string[] = [];
    myArray.push('string');
    
    const myArray: number[] = [];
    myArray.push(123);
    
    const myArray: Record<string, unknown>[] = [];
    myArray.push({key: 'value'});
    

    【讨论】:

    • 如果我想将整个 javascript 对象作为一个元素推送到数组中怎么办?
    • 它是类中的一个属性
    • @Roma 为您的问题更新了答案。如果这是一个类,也许你想在构造函数中myArray = []
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 2022-01-06
    • 2020-05-25
    相关资源
    最近更新 更多