Faisal Janjua
Faisal Janjua

Reputation: 3

store array into global variable angular

I am trying to save the value of parse array into global array. but global array showing me undefined

  dataUrl: string = "assets/data.csv";
  private data:[];
dataInit(){
    this.papa.parse(this.dataUrl, {
      download: true,
      complete: (result) => {
        // result.data.push(this.data);
        this.data = result.data
        // console.log(result.data, "inside parser");
        // console.log(this.data, "global array");
      }

    });
  }
  ngOnInit() {
    this.dataInit();
    console.log(this.data, "inside onInit");
}

Console

undefined "inside onInit"

Upvotes: 0

Views: 2414

Answers (5)

DHARMRAJ THAKUR
DHARMRAJ THAKUR

Reputation: 82

Because this.papa.parse function is asynchronous, you can't get value of data variable right after calling dataInit... better to do inside complete callback

dataUrl: string = "assets/data.csv";
private data:[];
dataInit() {
  this.papa.parse(this.dataUrl, {
    download: true,
    complete: (result) => {
      this.data = result.data
      this.toDo();
    }
  });
}

ngOnInit() {
  this.dataInit();
}

toDo(){
  console.log(this.data, "global array");
}

Upvotes: 0

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

The data will be available inside complete callback. So console.log(this.data) over there.

Reason: complete is a callback method which works asynchronously.

dataUrl: string = "assets/data.csv";
data = [];
dataInit(){
    this.papa.parse(this.dataUrl, {
      download: true,
      complete: (result) => {
        // result.data.push(this.data);
        this.data = result.data            
        console.log(this.data);
      }

    });
  }
  ngOnInit() {
    this.dataInit();
}

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86760

There are two reasons for that -

  1. You need to initilize the variable like this private data: Array<any>= [];
  2. You are binding the value into asyn method and consoling the value in synchronous way.

Upvotes: 1

Thabo
Thabo

Reputation: 1465

Put the console log inside the complete function of the async code.

Because the papa.parse download code is asynchronous, the console log will show the initial value of data because the results are not ready yet.

Upvotes: 0

Thabo
Thabo

Reputation: 1465

Change the initialization of the data property to something like

private data = [];

Or

private data: Array<T> = []

Instead of T type your array accordingly

Upvotes: 0

Related Questions