在Angular 2的文件中有两个类(一个装饰器/一个类两个装饰器)时,会发生什么情况? [英] What happens when there are two classes, one decorator/ one class two decorators in a file in Angular 2?

查看:177
本文介绍了在Angular 2的文件中有两个类(一个装饰器/一个类两个装饰器)时,会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

export class MyComponent {

}

因此,以上是我的实际组件文件.如果我要再上课

So, the above is my actual component file. If I have another class

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

export class MyComponent {

}

export class MyAnotherComponent {

}

@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 {

}

现在,我会收到任何错误消息吗?会发生什么?

Now, Do I get any error? What happens?

推荐答案

两个类和一个装饰器

@Component装饰器应用于紧随该装饰器的类.因此,在您的情况下,它将应用于MyComponent.现在,在模块声明中指定哪个类也很重要.如果指定MyComponent-一切都应该没问题.如果指定MyAnotherComponent-您将收到错误:

Two classes and one decorator

The @Component decorator is applied to the class that immediately follows the decorator. So in your case it's applied to MyComponent. Now, it also matters which class your specify in a module declarations. If you specify MyComponent - everything should be fine. If you specify MyAnotherComponent - you will get an error:

模块"AppModule"声明的异常值"MyAnotherComponent". 请添加@ Pipe/@ Directive/@ Component批注.

Unexpected value ‘MyAnotherComponent’ declared by the module ‘AppModule’. Please add a @Pipe/@Directive/@Component annotation.

因为Angular会抱怨该类不是组件的实例,因为未将装饰器应用于该类.

because Angular will complain that this class is not an instance of a component because the decorator wasn't applied to it.

您可以阅读有关@Component装饰器及其工作原理的更多信息这里.

You can read more about @Component decorator and how it works here.

简而言之,仅使用第一个装饰器.

In short, only the first decorator is used.

如果您在同一个类上使用两个装饰器,则这两个装饰器都将应用于该类,并以相反的顺序将元数据存储在该类中,从而使第一个装饰器属性存储在最后一个索引中.编译器解析元数据时,它将使用

If you use two decorators on the same class, both will be applied to the class and store metadata on that class in reverse order, so that the first decorator properties stored in the last index. When the compiler resolves metadata it takes the last metadata properties using the findLast function, which essentially picks the first decorator properties in your file.

因此,在您的情况下,仅支持my-cmp.如果在html my-cmpnt标记中使用,则会收到错误消息:

So in your case only the my-cmp will be supported. If you use in your html my-cmpnt tag, you will get an error:

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

Template parse errors: 'my-cmpnt' is not a known element:

这篇关于在Angular 2的文件中有两个类(一个装饰器/一个类两个装饰器)时,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆