首页 > 解决方案 > 有角度的 Http 客户端

问题描述

我对异步 Angular http 客户端的理解有问题。我有用 Java 编写的后端部分,其中端点返回具有相同格式但含义不同的数据。所以我决定创建以下代码:

  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);
  }
}

下一步是注入this.temperatureDailyCharts[0]子组件,并等待ngOnChange. 此代码无法正常工作,因为ngOnChanges方法永远不会调用。如果我将订阅部分更改为显式符号值

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

没关系。请解释一下为什么这个(从我的角度来看两个代码是相同的)构造不好?

标签: angularhttpasynchronoussubscribe

解决方案


JavaScript 按值传递函数参数。对于对象,我们有按值复制的对象引用(内存地址)。在这种情况下this.temperatureDailyCharts是对对象的引用,该引用被复制到getDailyParameterCharts()函数的激活记录中。在分配中,您覆盖(重新分配)这个复制的引用 - 这当然不会影响原始引用(这是 中的本地值ngOnInit())。

编辑:有时“按值传递引用”也称为“按引用传递”。您可以在此处阅读更多信息:https ://codeburst.io/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c


推荐阅读