javascript - TypeError:“属性”是只读的
问题描述
我将角度从 8 更新到 12,并且在项目的许多地方,控制台中出现错误:TypeError:“property_name”是只读的。
这是一个有错误的对象的示例:
export interface ObjectName {
index: number;
name: string;
widgets: ArrayType[];
}
这是发生错误的代码:
ngOnChanges(): void {
this.Areas = this.areas
.map(area => {
area.index = 10; // ERROR "index" is read-only
switch (area.name) {
case '1': area.index = 0; break;
case '2': area.index = 1; break;
case '3': area.index = 2; break;
}
return area;
})
.sort((a, b) => (a.index - b.index));
}
而且现在项目中有很多这样的地方,我不明白如何修复它。我尝试将接口更改为一个类,但一切都是一样的。这是我的 tsconfig.json,但我阅读了它的各种设置,似乎没有什么可以帮助我。
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"downlevelIteration": true,
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2020",
"emitDecoratorMetadata": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": ["node_modules/@types"],
"lib": ["es2018", "dom"]
}
}
解决方案
您将需要返回一个新对象(重新分配)。像这样的东西会起作用:
.map(area => {
let index = 10;
switch (area.name) {
case 'header_area': index = 0; break;
case 'content_area': index = 1; break;
case 'footer_area': index = 2; break;
}
return {...area, index};
})
扩展运算符...
会将 的内容分配给area
新对象并index
用新值覆盖。Extra:index: index
是多余的,但是如果局部变量具有不同的名称,则需要执行 eg index: newIndex
。
推荐阅读
- javascript - Python ctypes.c_int 到 Perl XS(或非 XS)的转换(Javascript 有符号的 32 位位移运算符转换)
- iis - 经典 ASP:响应时间周期性地减慢到极点
- sorting - 剑道图表排序目录“asc/desc”不排序
- python - 如何对 numpy 数组进行 nD 距离和最近邻计算
- c# - 如何获取列条目之一相同的行数
- java - 错误 RetroFit 开始数组对象 .IllegalStateException
- html - Angular 4中div背景图像的占位符
- c# - 单元测试 - 有时有效,有时无效
- c# - 我没有收到响应 REST API (POST) 内容类型 FormUrlEncode
- android - 向 REST 身份验证端点发送凭据时如何处理密码安全问题?