温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Angular中如何使用方法装饰器

发布时间:2022-06-23 09:56:10 来源:亿速云 阅读:155 作者:iii 栏目:web开发

这篇“Angular中如何使用方法装饰器”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Angular中如何使用方法装饰器”文章吧。

Angular中如何使用方法装饰器

什么是装饰器

在es6中,装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法;装饰器其实就是一个编译时执行的函数,语法“@函数名”,通常放在类和类方法的定义前面。装饰器有两种:类装饰器和类方法装饰器。

在 Angular 中,最常见的装饰器有 @Component 类装饰器,并且我们还能够为方法添加装饰器:

Angular中如何使用方法装饰器

装饰器是一个函数,方法装饰器可以用来监视、修改或者替换方法的定义

使用方法装饰器的优点

在上面的作用中提到了,方法装饰器能够用来监视,修改,或者替换方法的定义,这样我们能够灵活运用它带给我们的这一层封装来做很多事情。

最常见的就是校验,我们能够通过这一层封装一个方法,来进行统一的权限校验,这样在哪个方法上面需要添加权限校验的话,就只需要加上这个方法装饰器,而不需要重复去重写校验方法。

再或者就是统一的弹窗或者提示处理,对于很多不同的方法可能在执行结束之后都要进行统一的提示处理,这样就可以统一添加一个方法装饰器来进行统一处理。

总而言之,方法装饰器也就是为了封装部分方法上的统一逻辑,方便再每个方法调用的过程中需要的时候去进行复用。

方法装饰器的使用

方法装饰器主要有三个入参

  • target: Object - 被装饰的类的对象

  • key:string - 方法名

  • descriptor: TypePropertyDescript - 属性描述符

import { Component, OnInit } from '@angular/core';

function log(target: any, key: string, descriptor: any) {
  console.log(target);
  console.log(key);
  console.log(descriptor);
}
@Component({
  selector: 'app-fn-test',
  templateUrl: './fn-test.component.html',
  styleUrls: ['./fn-test.component.scss']
})
export class FnTestComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
    this.pay(2,3)
  }
  
  @log
  pay(Price: number, count:number): number {
      return Price*count
  }
}

Angular中如何使用方法装饰器

并且方法装饰可以细分为两种,一种是传入参数的方法装饰器,另一种是不传入参数的。

不传入参数

属性描述符中有一个属性 descriptor.value 就是被装饰的方法,通过这个方法,我们就能够拿到传入的参数以及函数的执行结果:

function log(target: any, key: string, descriptor: any) {
  let method = descriptor.value;
  descriptor.value = function (...args: any[]) {
      var result: any = method.apply(this, args);
      console.log(`method:${key}, args:${JSON.stringify(args)}, return:${result}`);
      return result;
  }
}

传入参数

在传入参数的这种情况下,我们需要在之前的函数外面再包装一层,外层函数能够拿到传入的值,内层返回的函数就是和之前的不带参数的函数时想用的,能够拿到三个参数:

function log(nowTime: Date) {
  console.log(nowTime);
  return function(target: any, key: string, descriptor: any){
    let method = descriptor.value;
    descriptor.value = function (...args: any[]) {
        var result: any = method.apply(this, args);
        console.log(`method:${key}, args:${JSON.stringify(args)}, return:${result}`);
        return result;
    }
  }
}

export class FnTestComponent implements OnInit {

  ...    
  @log(new Date())
  pay(Price: number, count:number): number {      return Price*count
  }
}

// Tue Jun 07 2022 18:48:22 GMT+0800 (中国标准时间)
// fn-test.component.ts:9 method:pay, args:[2,3], return:6

以上就是关于“Angular中如何使用方法装饰器”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI