Angular10--装饰器(注解)

928 阅读1分钟

什么是装饰器(注解)? 装饰器/注解就是一个函数,但是它返回函数的函数。

注:它不是Angular的特性,而是TypeScript的一个特性。

创建注解,可以带参数,decorators/index.js

export function Emoji(){
    return (target: object, key: string)=> {
        let val = target[key];

        const getter = ()=> {
            return val;
        }
        const setter = (value: string)=> {
            val = `😂 ${value} 😂 `
        }
        Object.defineProperty(target, key, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        })
    }
}
export function Confirmable(message: string){
    return (target: object, key: string, descriptor: PropertyDescriptor)=> {
        const original = descriptor.value;
        descriptor.value = function(...args: any){
            const allow = window.confirm(message);
            if(allow){
                return original.apply(this, args);
            }
            return null;
        }
        return descriptor;
    }
}

在组件中使用这个注解

import { Emoji, Confirmable } from './decorators';
@Component({
  ...
  selector: 'app-root',
  template: `<div>
  	{{zhujie}}
    <button (click)="onConfirmable()">弹出对画框</button>
   </div>`,
})
export class AppComponent{
  ...
  @Emoji() zhujie = '我是一个注解'
  
  @Confirmable('你确定要执行吗?')
  onConfirmable(){
    console.log('xxxx');
  }
}