全部,
尝试绑定(bind)到模型上的函数时出现错误
我有以下组件、模型和 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 EXCEPTION: Error in ./MyComponent class MyComponent- inline template:94:56 caused by: self.context.$implicit.getSomeValue is not a function
无法绑定(bind)到 .getSomeValue()
还是我做错了?
我假设基于这个 self.context.$implicit.
它以某种方式失去了它的上下文并且没有在模型上调用方法而是试图在“它是 self ”上调用它无论如何是吗?
谢谢
小号
编辑:添加代码以显示如何实例化 testModels
最佳答案
as TestModel[]
不会使其成为 TestModel
。它只是告诉 typescript 编译器(和 linter)它可以安全地假设 r.json
是 TestModel[]
。
关于Angular 2 模型函数插值 - self.context.$implicit.X 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235416/