如何解决无法为通过扩展运算符
当通过 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 方),因此代码添加了两个新属性,进行计算以将值分配给其中一个属性并使用来自另一个端点的数据为第二个属性分配一个值(基于在每个端点的负载中找到的匹配键值对。
解决方法
我做了一些修改,我认为它有效。您的设计非常奇怪且无效,映射和重新映射您已有的内容,而忽略了无需任何帮助代码即可访问的有用内容。这是 result,但让我们一步一步来:
// 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
作为参数发送到您的函数,您无需再次搜索它。然后不要尝试独立地将值分配给对象,只需返回您想要的值并直接在扩展运算符中分配它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。