Home > Blockchain >  Array is null when calling `.push`
Array is null when calling `.push`

Time:01-04

I am working on an angular app. In my component .ts file I have an array as follow:

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

In one of my method whenever I am trying to push a element in this array, it is giving me following error:

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

I don't see any mistake in my code. I always define a new array like this but first time I am getting this error. How to resolve this?

CodePudding user response:

the declaration should be like below

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

you should directly loop the response of the api like below (please check inside there are may be more keys inside response object, access the array through key)

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

CodePudding user response:

I'm not sure what syntax public myArray = []; is. Below will work for typescript.

const myArray: string[] = [];
myArray.push('string');

const myArray: number[] = [];
myArray.push(123);

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