【问题标题】:Angular 2 model function interpolation - self.context.$implicit.X is not a functionAngular 2 模型函数插值 - self.context.$implicit.X 不是函数
【发布时间】:2017-03-07 05:37:09
【问题描述】:

全部,

我在尝试绑定到模型上的函数时遇到错误

我有以下组件、模型和 Html(本例中都是假的)

export class TestModel {    
  public getSomeValue(): string {
     return "Hello World";
  }
}

让我们假设 testModels 属性以某种方式获取它的数据。

@Component(...)
public class MyComponent {    
  public testModels: TestModel[];

  ngOnInit() {
    this.loadData();
  }

  public loadData(): void
  {
     this.http.get("...")
     .map(r=>r.json as TestModel[]) // <--- I think now you've asked the question, I see the problem on this line
     .subscribe(d=>this.testModels = d);

  }
}

现在在我的html中

<div *ngFor="let testModel of testModels">
  <span>{{testModel.getSomeValue()}}</span> <!-- This fails -->
</div>

这是完整的错误:

error_handler.js:48 例外:错误 ./MyComponent class MyComponent- inline template:94:56 原因: self.context.$implicit.getSomeValue 不是函数

无法绑定到.getSomeValue() 还是我做错了?

我假设基于这个self.context.$implicit.,它以某种方式失去了它的上下文,而不是在模型上调用方法,而是试图在“它自己”上调用它,那是什么?

谢谢

S

编辑:添加代码以显示如何实例化 testModels

【问题讨论】:

  • 你是如何实例化testModels的?
  • TestModel 实例从何而来?来自 JSON?
  • 是的,它实际上是一个网络服务。我将更新代码示例以显示

标签: angular typescript angular2-template string-interpolation


【解决方案1】:

as TestModel[] 不会成为TestModel。它只是告诉 typescript 编译器(和 linter)它可以安全地假设 r.jsonTestModel[]

另见JSON to TypeScript class instance?

【讨论】:

  • 谢谢@Günter Zöchbauer
【解决方案2】:

你可以在你的 typescript 类中添加一个 getter

export class Person {
    firstname: string;
    lastname: string;
    get name(): string {
        return `${this.firstname} ${this.lastname}`;
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 2016-12-13
    • 2017-07-19
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2017-01-27
    • 2023-03-03
    相关资源
    最近更新 更多