【问题标题】:TypeError: Cannot read property '****' of undefined in Angular project when using inside forEachTypeError:在 forEach 内部使用时无法读取 Angular 项目中未定义的属性“****”
【发布时间】:2020-11-24 09:14:42
【问题描述】:

当我尝试遍历 this.data.members 并在 this.addedUsers 上的 forEach 中执行一些操作时,我收到 TypeError: Cannot read property未定义的“已添加用户”。我可以在 foarEach 之外访问 this.data.members

export class AddgroupComponent implements OnInit {
public addedUsers: any[] = [];

constructor(
    @Inject(MAT_DIALOG_DATA) public data: any
    ) { }

ngOnInit(): void {
       this.data.members.forEach(function (item) {
        console.log(this.addedUsers)
      });
    }
  }
}

【问题讨论】:

  • this inside JS function 指的是函数的作用域。使用箭头函数this.data.members.forEach(item => {...bind 函数来引用类成员变量。
  • 感谢您的回复..使用第一个箭头函数技术工作@MichaelD

标签: angularjs angular typescript typeerror


【解决方案1】:

由于您尝试使用 function (item) 的 ES5 语法访问 forEach 内的 this 上下文,因此 this 将因 laxical scoping 而未定义。要访问this,您必须使用箭头功能 () => {} ES6 功能。

ngOnInit(): void {
       this.data.members.forEach((item) => {     // use of () => { ... }arrow function
        

        // probably you want to push members
        // this.addedUsers.push(item) ;

         console.log(this.addedUsers)

      });
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多