【问题标题】:in angular5, I cannot access methods in a foreach loop在 angular5 中,我无法访问 foreach 循环中的方法
【发布时间】:2018-09-30 00:48:56
【问题描述】:

当我使用 httpClient 获取一个对象数组时,我可以访问数组中每个对象的属性,但我无法访问方法。我不明白为什么,我该怎么做。

this.interventionService.getInterventions().subscribe(interventions =>
        { 
            interventions.forEach(it => {

               console.log(it.InterventionId); // property can be accessed
               console.log(it.myMethod()); // myMethod cannnot be accessed

               // I get an error: 'myMethod is not a function'

            });
        });

但是,如果我创建一个新对象,我可以访问这些方法:

var it = new Intervention();
it.myMethod(); // no error

感谢您的帮助

【问题讨论】:

  • Intervention的接口是什么?
  • 还有getInterventions()的实现是什么?
  • 你需要类似:... .getInterventions().map(items => items.map(i => new Intervention(i)).subscribe ...
  • 对模型使用接口而不是类。将方法放入服务中。
  • 您必须手动将您的对象映射到您的类。 Angular httpClient 只是将数据解析为对象。它对你的方法一无所知

标签: angular


【解决方案1】:

您需要为使用bind 的方法设置正确的this 上下文。

this.interventionService.getInterventions().subscribe(interventions => {
  interventions.forEach(it => {
      it.myMethod.bind(it)();
  });
});

【讨论】:

  • 如果他也在构造函数中做了一些事情......或者在那个干预类上有getter/setter怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多