0

I have problem with understanding of async angular http client. I had backend part written in Java where endpoints return data with the same format but different meaning. So I decided to create follow code:

  export class AppComponent implements OnInit{

  temperatureDailyCharts: Chart[] = new Array();

  constructor(private weatherService: WeatherService){}

  ngOnInit(): void {
    this.getDailyParameterCharts("temperature", this.temperatureDailyCharts);

  }

  getDailyParameterCharts(parameter: string, chartList: Chart[]) {
    this.weatherService.getDailyParameter(1, parameter)
      .subscribe(response => chartList = response);
  }
}

Next step is injecting this.temperatureDailyCharts[0] to child component, and waiting for ngOnChange. This code doesn't work correctly, because ngOnChanges method will never invoke. If I change my subscribe part to explicity sign value

.subscribe(response => this.temperatureDailyCharts = response);

it is ok. Please, explain me why this (from my point of view both codes are the same) construction is bad?

  • Possible duplicate of [Javascript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – JB Nizet Jun 10 '18 at 15:40
  • JavaScript passes arguments by value, just like Java. Assigning a new value to chartList will modify the value of the **local variable** chartList, not the value of this.temperatureDailyCharts, just as in Java. This has nothing to do with HTTP. Just with how JavaScript arguments are passed to functions. – JB Nizet Jun 10 '18 at 15:42

1 Answers1

0

JavaScript passes function arguments by value . In case of objects, we have object references (memory addresses) which are copied by value. In this case this.temperatureDailyCharts is a reference to an object, this reference gets copied into the activation record of the getDailyParameterCharts() function. In the assignments, you override (re-assign) this copied reference - which of course doesn't have effect on the original reference (which is a local value in ngOnInit()).

Edit: sometimes "passing a reference by value" is also called "passing by reference". You can read more here: https://codeburst.io/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c

erosb
  • 2,943
  • 15
  • 22