Angular自定义装饰器(注解)

在Angular中装饰器就是一个函数,他可以作用于类,类的属性和方法,在不改变原函数的功能上在增加额外的一些功能,装饰器会把你装饰的属性或方法的当前组件和key当做参数传进去,详见代码吧

import { Component, OnInit } from '@angular/core';
import {MyName,confirm} from "../../decorator";


@Component({
  selector: 'app-decorator',
  templateUrl: './decorator.component.html',
  styleUrls: ['./decorator.component.css']
})
export class DecoratorComponent implements OnInit {

  constructor() { }

  @MyName() name='夏良辰'
  ngOnInit(): void {
  }
  @confirm("你确定退出吗")
  handleClick() {
    console.log('执行了handle函数')
  }
}

 

//装饰属性
//target和key是必须滴
export function MyName() {
  return (target:object,key:string)=>{
    //得到当前装饰器后key的值
    let value=target[key]
   const getter=()=>{
      return value
   }
   const setter=(name)=>{
      value=`我的名字叫${name}`
   }
   Object.defineProperty(target,key,{
     get:getter,
     set:setter,
     configurable:true,
     enumerable:true
   })
  }
}

//跟函数
export function confirm(message:string) {
  return (target:object,key:string,descriptor:PropertyDescriptor)=>{
    //key是函数名
    //descriptor代表函数的属性描述符
    //保存原函数
    let oldFunction=descriptor.value
    //重写函数
    descriptor.value=function () {
      //是否执行后面函数(这里增加一个确认功能)
      const flag=window.confirm(message)
      if (flag){
        //注意这里this调用要用原函数的this
        return oldFunction.apply(this)
      }
      return  null
    }
  }
}

 

posted on 2020-10-18 23:04  夏天不热哒  阅读(788)  评论(0)    收藏  举报

导航