当 Angular 2 中的一个文件中有两个类、一个装饰器/一类两个装饰器时会发生什么?

2024-04-02

@Component({
   selector: 'my-cmp',
   template: '<div>Hello World!</div>'
}) // here component metadata

export class MyComponent {

}

所以,上面是我实际的组件文件。如果我还有别的课

@Component({
   selector: 'my-cmp',
   template: '<div>Hello World!</div>'
}) // here component metadata

export class MyComponent {

}

export class MyAnotherComponent {

}

and

@Component({
   selector: 'my-cmp',
   template: '<div>Hello World!</div>'
}) // here component metadata
@Component({
   selector: 'my-cmpnt',
   template: '<div>Hello Something!</div>'
}) // here component metadata

export class MyComponent {

}

现在,我有任何错误吗?会发生什么?


两个类和一个装饰器

The @Component装饰器应用于紧随装饰器之后的类。所以在你的情况下它适用于MyComponent。现在,在模块声明中指定哪个类也很重要。如果您指定MyComponent- 一切都应该没问题。如果您指定MyAnotherComponent- 你会得到一个错误:

模块“AppModule”声明了意外值“MyAnotherComponent”。 请添加@Pipe/@Directive/@Component注释。

因为 Angular 会抱怨这个类不是组件的实例,因为装饰器没有应用于它。

您可以阅读更多有关@Component装饰器及其工作原理here https://hackernoon.com/implementing-custom-component-decorator-in-angular-4d037d5a3f0d.

两个装饰器和一个类

简而言之,只使用了第一个装饰器。

如果您在同一个类上使用两个装饰器,则两者都将应用于该类并存储该类的元数据以相反的顺序,以便第一个装饰器属性存储在最后一个索引中。当编译器解析元数据时,它使用最后的元数据属性findLast https://github.com/angular/angular/blob/4.2.0-rc.1/packages/compiler/src/directive_resolver.ts#L42函数,它本质上是选择文件中的第一个装饰器属性。

所以在你的情况下只有my-cmp将得到支持。如果你在你的html中使用my-cmpnt标签,你会得到一个错误:

模板解析错误:“my-cmpnt”不是已知元素:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 Angular 2 中的一个文件中有两个类、一个装饰器/一类两个装饰器时会发生什么? 的相关文章

随机推荐