方法装饰器在后端编程中见到是比较多的,路由、注入等场景都有大规模的应用。下面是开始学习TS的方法装饰器。
一个函数,返回 TypedPropertyDescriptor | void 参数如下:
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
不知道什么意思,先写一个简单的例子打印下,看看每一个参数是什么意思,
示例代码:
const get:MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
console.log("target:",target);
console.log("propertyKey:",propertyKey);
console.log("descriptor:",descriptor);
}
class HttpRequest {
@get
getAllData(params:{data:[]}){
}
}
打印结果:
参数意义:
示例思路:
代码示例:
const get:MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
const method = descriptor.value
descriptor.value = () => {
method({header:'这是请求头header',body:'请求内容'})
}
}
interface Request {
header:string,
body:string
}
class HttpRequest {
@get
getAllData(request?:Request){
console.log(request);
}
}
let http = new HttpRequest()
http.getAllData()
方法装饰器工厂类似于类装饰器工厂,工厂加工产生的是方法装饰器。这个工厂需要参数提供条件。
示例思路,之前的例子,我们需要跟上请求路径。
示例代码:
const get: (path: string) => MethodDecorator = (path) => {
return (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
const method = descriptor.value;
(function () {
method({ header: "这是请求头header", path: path, body: "请求内容" });
})();
};
};
interface Request {
header: string;
path: string;
body: string;
}
class HttpRequest {
@get("/getAll")
getAllData(request?: Request) {
console.log(request);
}
@get("/getList")
getList(request?: Request) {
console.log(request);
}
}
控制台打印输出: