首页 > 解决方案 > 无法为通过扩展运算符添加的两个新属性同时导出两个计算值

问题描述

当通过 Spread 运算符添加的两个属性具有单独的派生值时,第二个属性派生“似乎”首先停止。通过扩展运算符添加具有派生值的第二个属性会破坏第一个属性值

第二个是通过一个正在工作的函数添加的,只是它阻止了第一个属性值的计算。我有一种感觉,这是因为它是一个不同的过程(所以适用于另一个数组副本?)。cv19_actisus: OR 子代码是派生的,它是一个或另一个,但不是两者都有,是吗?

这是(见 hello.component)

堆栈闪电战

如果您注释掉subcode: this.updateCovidSubcodeData(),并替换它,subcode: '',cv19_actisus: Math.round(res.attributes.cv19_acti * 1.33)如果子代码具有任何静态值,例如,它可以工作,但是如果我尝试使用为子代码分配一个值subcode: this.updateCovidSubcodeData()

我确实看到了子代码的正确值,但没有看到 cv19_actisus

对于一点上下文,这是来自两个独立端点的数据,一个我可以控制,另一个我不能(第 3 方),因此代码添加两个新属性进行计算以将值分配给其中一个属性并使用来自另一个端点的数据以将值分配给第二个属性(基于在每个端点的有效负载中找到的匹配键:值对。

标签: angularspread

解决方案


我做了一些修改,我认为它正在工作。您的设计非常奇怪且无效,映射和重新映射您已有的内容,而忽略了无需任何帮助代码即可访问的有用内容。这是结果,但让我们一步一步来:

// First, let's chain those subscriptions since their results depend on each other
ngOnInit() {
  this.c19service.intCodes() // We'll get codes first
    .pipe(
      tap(covidCodes => (this.covidCodes = covidCodes)), // save them to private prop
      concatMap(() => this.c19service.getCovid19data()) // and call for features
    )
    .subscribe(
      featrues => this.onC19DataRetrieved(featrues), // let's work with features now
      error => (this.errorMessage = <any>error)
    );
}

如您所见,最好将这些订阅实际链接起来,因为它们相互依赖。在您的情况下,它们是独立执行的,这会导致forEach您可能在日志中看到的错误。您尝试循环尚未初始化的数组,因为第二个订阅(在您的情况下)尚未完成。

现在映射。那是您的代码中最无效的部分。你忽略了你所拥有的,做了一些消耗资源的映射和循环,导致无处可去。

onC19DataRetrieved(data: Feature[]) {
  console.log(this.covidCodes);
  this.covidCases = data["features"];
  this.filteredmCovid = this.covidCases;
  this.newShape = this.covidCases.map(res => ({
    attributes: {
      ...res.attributes,
      cv19_actisus: Math.round(res.attributes.cv19_acti * 1.33),
      // you are already in features loop, you have the access to codmun of current feature/person
      subcode: this.updateCovidSubcodeData(res.attributes.codmun) 
    }
  }));
  this.filteredmCovid = this.newShape;
}

updateCovidSubcodeData(codmun) {
  // Here, just find the codmun match. But codmun from person comes as number
  // and it's a string in codes array -> that's why I'm parsing it
  const code = this.covidCodes.find(code => parseInt(code.codmun) === codmun);
  // If there is no match, just return '-'
  return !!code ? code.subcode : "-";
}

如您所见,您的大部分代码都是无用的。正如评论中提到的,您在传播对象时已经拥有了您正在寻找的东西,因此只需将codmun作为参数发送到您的函数,您无需再次搜索它。然后不要尝试独立地将值分配给对象,只需返回您想要的值并直接在扩展运算符中分配它。


推荐阅读