angular - TSLint 无法识别订阅方法中数组的更新
问题描述
在我的 Angular 项目中,当我编写以下代码时,我收到了来自 TSLint的Mismatched query and update of collection错误:
export class SomeComponent implements OnInit {
private wishes: Wish[];
constructor(private service: Service) {}
ngOnInit() {
this.service.subscribe(wishes => {
this.wishes = wishes;
}
}
我得到一个集合“愿望”的内容被查询,但从未更新(我在代码中进一步查询)。但是,我不明白为什么会收到错误消息,因为每次收到订阅的愿望时我都会更新集合。它与订阅块内发生的更新有关吗?提前致谢。
解决方案
删除私人。如果您在全局变量中使用 private 并且没有 getter 和 setter 是不好的做法。
export class SomeComponent implements OnInit {
wishes: Wish[];
constructor(private service: Service) {}
ngOnInit() {
this.service.subscribe(wishes => {
this.wishes = wishes;
}
}
}
使用 getter 和 Setter:
export class SomeComponent implements OnInit {
private wishes: Wish[];
constructor(private service: Service) {}
ngOnInit() {
this.service.subscribe(wishes => {
setWishes(wishes);
}
}
getWishes(): Wish[] {
return this.wishes;
}
setWishes(wishes: Wish[]) {
this.wishes = wishes;
}
}
根据您运行的服务器,它可能会通过使用私人给您带来问题,所以我会坚持第一个解决方案。
您可以运行ng build --prod
以测试 prod 的代码
推荐阅读
- manim - 在 Manim 中完成动画时如何在 3d 空间中移动相机
- angular - 在 Angular 前端使用 CBOR 的示例代码
- ios - 有人可以解释我在尝试使用 bluetthooth 快速发送文本时做错了什么吗?
- python-3.x - 在同一字符串 A1,B1 中使用数字和字符对值进行排序
- java - 如何从 Paho MQTT 消息中解析 JSON
- powershell - Powershell Invoke-RestMethod 分页
- json - 如何从 JSON 中检索 MARKER 的经纬度并将这些标记放在 Google Maps Flutter 上
- python - 在python中创建DataFrame的数据透视表(将列带到行)
- sql - 如何使用 jsonb 在 postgres 中创建索引?
- python - 60fps 和更新列表。该怎么办?