首页 > 解决方案 > 更新组件中的变量后角度不更新

问题描述

我使用 Angular 9 并修改了我在模板中使用的变量。但不幸的是,我的模板没有更新。谁能解释一下让 Angular 知道我的组件中的某些内容发生了变化的典型方法是什么?

projects: any[] = [];
ngAfterViewInit(): void {
    this.actRoute.params.subscribe((params) => {
        this.electronService.foo.bar(
        .then((x) => {
            var history = x.y();

            history.on("begin", () => {
                this.projects.push('foo');
            });
            history.execute();
        });
    });
}

foo.component.html

<ul>
  <li *ngFor="let project of projects;">{{project}}</li>
</ul>

标签: angular

解决方案


您需要使用箭头功能。this与您认为的含义不同

ngAfterViewInit(): void {
    let projects = this.projects;
    projects = [];

    this.actRoute.params.subscribe((params) => {
        this.electronService.foo.bar(
          .then((x) => { // arrow function
            const history = x.y(); // use const

            history.on("begin", () => { // arrow function
              projects.push('foo');
            });
            history.execute();
          });
        });
    }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions


推荐阅读