我是Angular 2和TypeScript的新手,我试图遵循最佳做法.
@H_502_1@而不是使用简单的JavaScript模型({}),我试图创建一个TypeScript类.
@H_502_1@但是,Angular 2似乎并不喜欢它.
@H_502_1@我的代码是:
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; }@H_502_1@我正在使用它:
import { testWidget} from "lib/testWidget"; @Component({ selector: "myComponent",template: "<testWidget></testWidget>",directives: [testWidget] })@H_502_1@我从Angular得到一个错误:
@H_502_1@EXCEPTION: Can’t resolve all parameters for testWidget: (?).@H_502_1@所以我想,模型还没有定义…我会把它移到顶部! @H_502_1@除了现在我得到例外:
@H_502_1@ORIGINAL EXCEPTION: No provider for Model!@H_502_1@我该如何做到这一点? @H_502_1@编辑:感谢所有的答案.它使我走上正确的道路. @H_502_1@为了将其注入到构造函数中,我需要将它添加到组件上的提供者. @H_502_1@这似乎工作:
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) {} }
我会试试这个:
@H_502_1@将您的模型拆分成一个名为model.ts的单独文件:
export class Model { param1: string; }@H_502_1@将其导入到组件中.这将为您提供能够在其他组件中使用的附加益处:
Import { Model } from './model';@H_502_1@在组件中初始化:
export class testWidget { model: Model; model.param1 = "your string value here"; }@H_502_1@在html中正确访问它:
@Component({ selector: "testWidget",template: "<div>This is a test and {{model.param1}} is my param.</div>" })