Angular 2 模型函数插值 - self.context.$implicit.X 不是函数

Ste*_*tes 5 string-interpolation typescript angular2-template angular

全部,

尝试绑定到模型上的函数时出现错误

我有以下组件、模型和 Html(对于这个例子都是假的)

export class TestModel {    
  public getSomeValue(): string {
     return "Hello World";
  }
}
Run Code Online (Sandbox Code Playgroud)

让我们假设 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);

  }
}
Run Code Online (Sandbox Code Playgroud)

现在在我的 html

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

这是完整的错误:

error_handler.js:48 EXCEPTION: Error in ./MyComponent class MyComponent-inline template:94:56 引起的:self.context.$implicit.getSomeValue is not a function

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

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

谢谢

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

Gün*_*uer 5

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

另请参阅JSON to TypeScript 类实例?