angular - 无法为通过扩展运算符添加的两个新属性同时导出两个计算值
问题描述
当通过 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 方),因此代码添加两个新属性进行计算以将值分配给其中一个属性并使用来自另一个端点的数据以将值分配给第二个属性(基于在每个端点的有效负载中找到的匹配键:值对。
解决方案
我做了一些修改,我认为它正在工作。您的设计非常奇怪且无效,映射和重新映射您已有的内容,而忽略了无需任何帮助代码即可访问的有用内容。这是结果,但让我们一步一步来:
// 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
作为参数发送到您的函数,您无需再次搜索它。然后不要尝试独立地将值分配给对象,只需返回您想要的值并直接在扩展运算符中分配它。
推荐阅读
- visual-studio - 为什么没有在 Visual Studio 2019 中添加项目引用?
- php - 更新不适用于外键上的 INNER JOIN
- java - 我们如何在从应用程序传递电子邮件意图时动态设置来自电子邮件
- casting - 将 u32 重新解释为四个 u8 的数组
- java - 加载时编织(AspectJ):Hystrix 中断事务传播
- python - 在项目中执行“npm install”时出现“gyp ERR!stack SyntaxError: invalid syntax:”
- ios - 获取请求中的令牌标头不起作用。生成错误 403 响应
- php - 查找字符串中第一个重复的单词
- .net-core - 为源重试“FindPackagesByIdAsync”
- intellij-idea - 错误:无法启动 javac.exe。exec:“javac.exe”:在 intellij 上运行仪表命令后,在 %PATH 中找不到可执行文件