【发布时间】:2016-11-18 19:51:21
【问题描述】:
我是 Angular 2 和 TypeScript 的新手,我正在努力遵循最佳实践。
我尝试创建一个 TypeScript 类,而不是使用简单的 JavaScript 模型 ({ })。
但是,Angular 2 似乎并不喜欢它。
我的代码是:
import { Component, Input } from "@angular/core";
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>"
})
export class testWidget {
constructor(private model: Model) {}
}
class Model {
param1: string;
}
我将其用作:
import { testWidget} from "lib/testWidget";
@Component({
selector: "myComponent",
template: "<testWidget></testWidget>",
directives: [testWidget]
})
我收到来自 Angular 的错误:
例外:无法解析 testWidget 的所有参数:(?)。
所以我想,模型还没有定义……我会把它移到顶部!
除了现在我得到了异常:
原始异常:模型没有提供者!
我该如何做到这一点??
编辑:感谢大家的回答。它让我走上了正确的道路。
为了将它注入到构造函数中,我需要将它添加到组件上的提供者中。
这似乎有效:
import { Component, Input } from "@angular/core";
class Model {
param1: string;
}
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>",
providers: [Model]
})
export class testWidget {
constructor(private model: Model) {}
}
【问题讨论】:
标签: class typescript angular