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

标签 angular typescript angular2-template string-interpolation

全部,

尝试绑定(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.jsonTestModel[]

另见 JSON to TypeScript class instance?

关于Angular 2 模型函数插值 - self.context.$implicit.X 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235416/

相关文章:

Angular 8,启动时出现 IE11 错误 Function.prototype.toString : 'this' is not a Function object

javascript - 在 TypeScript 中将 IntelliSense 中的方法的别名显示为方法而不是属性

Angular Material 如何从 mat-table 设置 mat-sort-header

angular - fromEvent 未在带有 'change' 的指令内触发,但带有 'click' 是

javascript - 如何在 javascript 装饰器中使用 Angular2 依赖注入(inject)?

具有相同类型属性的接口(interface)或类型的 Typescript 简写

typescript - 使用漂亮时如何禁用vscode中装饰器后的尾随逗号

Angular 2 组件 : How to handle circular Inputs and Outputs

angular - if else 在 angular2 模板语法中

angular - 在 Angular 模板中创建本地绑定(bind)上下文