How do I declare a model class in my Angular 2 component using TypeScript?

后端 未结 8 705
野趣味
野趣味 2020-12-23 11:10

I am new to Angular 2 and TypeScript and I\'m trying to follow best practices.

Instead of using a simple JavaScript model ({ }), I\'m attempting to create a TypeScri

8条回答
  •  萌比男神i
    2020-12-23 11:49

    The problem lies that you haven't added Model to either the bootstrap (which will make it a singleton), or to the providers array of your component definition:

    @Component({
        selector: "testWidget",
        template: "
    This is a test and {{param1}} is my param.
    ", providers : [ Model ] }) export class testWidget { constructor(private model: Model) {} }

    And yes, you should define Model above the Component. But better would be to put it in his own file.

    But if you want it to be just a class from which you can create multiple instances, you better just use new.

    @Component({
        selector: "testWidget",
        template: "
    This is a test and {{param1}} is my param.
    " }) export class testWidget { private model: Model = new Model(); constructor() {} }

提交回复
热议问题