加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用TypeScript在我的Angular 2组件中声明一个模型类?

发布时间:2020-12-17 07:47:44 所属栏目:安全 来源:网络整理
导读:我是Angular 2和TypeScript的新手,我试图遵循最佳做法. 而不是使用简单的JavaScript模型({}),我试图创建一个TypeScript类. 但是,Angular 2似乎并不喜欢它. 我的代码是: import { Component,Input } from "@angular/core";@Component({ selector: "testWidge
我是Angular 2和TypeScript的新手,我试图遵循最佳做法.

而不是使用简单的JavaScript模型({}),我试图创建一个TypeScript类.

但是,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得到一个错误:

EXCEPTION: Can’t resolve all parameters for testWidget: (?).

所以我想,模型还没有定义…我会把它移到顶部!

除了现在我得到例外:

ORIGINAL EXCEPTION: No provider for Model!

我该如何做到这一点?

编辑:感谢所有的答案.它使我走上正确的道路.

为了将其注入到构造函数中,我需要将它添加到组件上的提供者.

这似乎工作:

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) {}
}
我会试试这个:

将您的模型拆分成一个名为model.ts的单独文件:

export class Model {
    param1: string;
}

将其导入到组件中.这将为您提供能够在其他组件中使用的附加益处:

Import { Model } from './model';

在组件中初始化:

export class testWidget {
   model: Model;
   model.param1 = "your string value here";
}

在html中正确访问它:

@Component({
      selector: "testWidget",template: "<div>This is a test and {{model.param1}} is my param.</div>"
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读