在Angular 2中,我可以创建一个组件,如下所示:
@H_404_1@import {Component,Template} from 'angular2/angular2'
@Component({
selector: 'my-component'
})
@View({
inline: "<div>Hello my name is {{name}}</div>"
})
export class MyComponent {
constructor() {
this.name = 'Max'
}
sayMyName() {
console.log('My name is',this.name)
}
}
(来源:http://blog.ionic.io/angular-2-series-components/)
然后将其编译为常规ES5.
我的问题分为两部分:
>这些装饰师是特定于角度的.他们如何定义?
>如何定义我自己的装饰器?
事实上,你应该调用“注释”装饰器,因为它有点不同;-)它们允许装饰对象.这个博文可以在这里给出更多的提示:
http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html.
所以装饰者并不是Angular所特有的.有一个ES7的建议,它们也受到TypeScript语言的支持.这可以与reflect-metadata库(它包含在angular2-polyfills.js文件中)结合使用,以设置和获取元素的元数据.
>装饰师
@H_404_1@export function MyClassDecorator(value: string) { return function (target: Function) { Reflect.defineMetadata("MyClassDecorator",value,target); } } @Component({ ... }) @MyClassDecorator("my Metadata") export class AppComponent { constructor() { let decoratorValue: string = Reflect.getMetadata("MyClassDecorator",this.constructor); } }>功能装饰器
@H_404_1@export function log(target: Object,propertyKey: string,descriptor: TypedPropertyDescriptor<any>) { var originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log("The method args are: " + JSON.stringify(args)); var result = originalMethod.apply(this,args); console.log("The return value is: " + result); return result; }; return descriptor; } export class AppComponent { constructor() { } @MyMethodDecorator getMessage() { return 'test'; } }>参数装饰器
@H_404_1@export function MyParameterDecorator(param1) { return function(target: any,methodKey: string | symbol,parameterIndex: number) { (...) }; }>类属性装饰器
@H_404_1@export function MyPropertyDecorator(target: any,propertyKey: string | symbol) { (...) }所以一般来说,装饰器对应一个功能.如果不使用参数,则不需要返回包装.如果要为装饰器使用参数,则需要一个附加函数来获取参数并返回实际装饰器:
@H_404_1@// In the case of a parameter decorator // myMethod(@MyDecoratorWithoutParameter someParam) { ... } export function MyDecoratorWithoutParameter(target: any,propertyKey: string | symbol,parameterIndex: number) { console.log('decorator called'); } // myMethod(@MyDecoratorWithParameter('test') someParam) { ... } export function MyDecoratorWithParameter(param1) { // param1 contains 'test' return function(target: any,parameterIndex: number) { console.log('decorator called'); }; }这是一个与我的样品对应的plunkr:https://plnkr.co/edit/0VBthTEuIAsHJjn1WaAX?p=preview.
以下是可以使用TypeScript为您提供更多详细信息的链接:
> How to implement a typescript decorator?
> How to avoid hard coded this? in Decorators
> http://blogs.msdn.com/b/typescript/archive/2015/04/30/announcing-typescript-1-5-beta.aspx
希望它帮助你,蒂埃里