首页 > 解决方案 > 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;
        }
    }

我得到一个集合“愿望”的内容被查询,但从未更新(我在代码中进一步查询)。但是,我不明白为什么会收到错误消息,因为每次收到订阅的愿望时我都会更新集合。它与订阅块内发生的更新有关吗?提前致谢。

标签: angularwarningstslint

解决方案


删除私人。如果您在全局变量中使用 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 的代码


推荐阅读