[Decorator in Angular] - Property decorator (Property decorators)

        Attribute decorators, as the name suggests, are used to decorate the attributes of a class. It receives two parameters:

        target : the object of the class to which the decorated property belongs

        key : the property name to be decorated

1. Attribute decorator without parameters

        The following example demonstrates tracking modification of a property via a property decorator:

function changeLog(target: any, key: string) {
    var _value: string = target[key];
    if(delete target[key]) {
        Object.defineProperty(target, key, {
            get: function () {
                return _value;
            },
            set: function (value) {
                _value = value;
                console.log(`set ${key} = ${value}`);
            }
        });
    }
}
 
export class Grape {
    @changeLog
    price: number = 0;
    constructor(price: number) {
        this.price = price;
    }
}
 
//组件中调用代码
let grape = new Grape(4);
grape.price = 8;

        Running the program prints the following:

 2. Attribute decorator with parameters

        Of course, property decorators can also pass parameters. The following example demonstrates passing parameters through property decorators to restrict users from modifying property values. An exception will be thrown if the maximum and minimum values ​​are exceeded:

function changeLog(config: { max?: number, min?: number }) {
    return function (target: any, key: string) {
        var _value: string = target[key];
        if (delete target[key]) {
            Object.defineProperty(target, key, {
                get: function () {
                    return _value;
                },
                set: function (value) {
                    if (config.max && value > config.max) {
                        throw `try to set price too high, max: ${config.max}, try: ${value}`;
                    }
                    if (config.min && value < config.min) {
                        throw `try to set price too low, min: ${config.min}, try: ${value}`;
                    }
                    _value = value;
                    console.log(`set ${key} = ${value}`);
                }
            });
        }
    }
}

export class Grape {
    @changeLog({ min: 6 })
    price: number = 6;
    
    constructor(price: number) {
        this.price = price;
    }
}

//组件中调用代码
let grape = new Grape(4);
grape.price = 8;

        Running the program prints the following:

         In the example above, the price attribute decorator sets a minimum value of 6 , and calls new Grape(4) in the component , which is smaller than the minimum value, so a setting exception message is thrown.

         The use of attribute decorators is introduced here, welcome to exchange opinions.

Guess you like

Origin blog.csdn.net/evanyanglibo/article/details/122585679