3

I'm having a problem with updating the contents of an array in an Angular component.

The array with name arr is created to store the values that is used by the dataset for the ChartJS chart.

On ngOnInit, I run retrieveTempDataReturn() function which returns _arr, an array of retrieved values, from a data service, and I assign the _arr array into arr array I declared on top.

After the page has loaded, I run displayArray() function which displays the contents of the arr array, using click event on a button. The output in the browser console is as follows:

Array contents: 22.1,22.1,23.1,24.1,25.1,26.1,25.1,24.1,22.1,21.1 

Thus, I can see that the retrieved data is successfully updated into the arr array.

Then, I run another function using click event on a button, retrieveHumidDataAssign() which retrieves another set of data from the same data service and assigns the data into the arr array right away. Later in the function, I console.log() the contents of the arr array and I can see the values updated in the arr array. The output in the browser console is as follows:

Array assigned Humid: 56,56,56,56,56,56,56,56,56,56

But then when I the displayArray() again to view the content in the arr array, the content is still the original content. The output in the browser console is as follows:

Array contents: 22.1,22.1,23.1,24.1,25.1,26.1,25.1,24.1,22.1,21.1

The content of arr array seemed to be changed in the console.log part of retrieveHumidDataAssign(). But it is somehow not changed when I separately run another function to display its contents.

Why does this happen? And how do I update the content in the array? Please help me.

Below is the component file:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import {BaseChartDirective} from 'ng2-charts/ng2-charts';

@Component({
  templateUrl: 'chartjs.component.html'
})
export class ChartJSComponent {

  arr = [];

  constructor(private dataService: DataService){
  }

  ngOnInit(){
    this.arr = this.retrieveTempDataReturn();
  }

//function that retrieves and returns array of temperature values
  retrieveTempDataReturn(){
    var _arr = new Array();
    this.dataService.getData().subscribe(function(response){
      console.log("Response: " + JSON.stringify(response));
      for(var item of response){
        console.log("Pushing " + item.Temperature);
        _arr.push(item.Temperature);
      }
      console.log("Array returned: " + _arr);
    });
    return _arr;
  }

//function that retrieves and assign array into the "arr" array
  retrieveHumidDataAssign(){
    var _arr = new Array();
    this.dataService.getData().subscribe(function(response){
      console.log("Response: " + JSON.stringify(response));
      for(var item of response){
        _arr.push(item.Humidity);
      }
      this.arr = _arr;
      console.log("Array assigned Humid: " + this.arr);
    });
  }

//display the data on the chart by using "arr" array in the dataset for the chart
  refreshChart(){
    console.log("To display: " + this.arr);
    this.datasets = [{
      label: "Values",
      data: this.arr 
    }];
  }

//function to display the contents of the array
  displayArray(){
    console.log("Array contents: " + this.arr);
  }

//arrays that are used by Chart JS chart for data visualization
  private datasets = [
    {
      label: "Values",
      data: []
    }
  ];

  private labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];

  private options = {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  };

}

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

3
  • where and how did you called function displayArray and retrieveHumidDataAssign? Commented Jul 27, 2017 at 2:30
  • I call the function via a button on the .html using click event. Commented Jul 27, 2017 at 2:33
  • I call the functions via their repective buttons on the .html using click event. For example, ` <button (click)="retrieveHumidDataAssign()">Retrieve Humid</button> <button (click)="displayArray()">displayArray</button>` Commented Jul 27, 2017 at 2:39

1 Answer 1

3

Here you have to keep the context while using this in callbacks, else this will turn to callback function itself。

you can use arrow function here

//function that retrieves and assign array into the "arr" array
retrieveHumidDataAssign(){
  var _arr = new Array();
  this.dataService.getData().subscribe(response => {     // <----arrow function here
    ...
    this.arr = _arr;
    console.log("Array assigned Humid: " + this.arr);
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

OMG!!! Thanks a lot! That solves the problem! But what is the difference between function(response) {} and response => {}. I thought they are the same?
@KelvinWeiMinn this will change while using it in callbacks, you can confirm by console.log(this) in callback function. While arrow function will here you keep your original context while in callbacks.
Thank you! Thank you! You saved my life!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.