R
R
Roman Rakzin2022-01-27 09:25:33
typescript
Roman Rakzin, 2022-01-27 09:25:33

How can you write a decorator that wraps the specified function in a certain code?

How can you write a decorator that wraps the specified function in a certain code?

this.ngZone.runOutsideAngular(() => {
    ......Code.....
}

What would look like this

@RunOutsideAngular
myFunc() {
    mycode.....
}

and in the end it would work like this

myFunc() {
    this.ngZone.runOutsideAngular(() => {
        mycode.........
    }
}

And the second question - is it possible to wrap the entire class so that all the functions of the class are wrapped in a wrapper?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2022-01-28
@TwoRS

Conditionally like this:

const RunOutsideAngular = (target: any, memberName: string) => {
  const method = target[memberName];
  return Object.defineProperty(target, memberName, {
    writable: true,
    configurable: true,
    value(...args: any[]) {
        return this.ngZone.runOutsideAngular(method.bind(this, ...args))
    } 
  });
};

const RunOutsideAngularAll = (constructor: Function) => { 
    const keys = new Set<string>(); 
    let proto = constructor.prototype;

    do {
        if(proto === Object.prototype) break;

        Object.getOwnPropertyNames(proto).forEach(
            key => typeof proto[key] === 'function' 
                && key !== 'constructor'
                && keys.add(key)
        );
    } while (
        proto = Object.getPrototypeOf(proto)
    );

    keys.forEach(key => RunOutsideAngular(constructor.prototype, key));
}

class SomeClass {
    @RunOutsideAngular
    myFunc() {
        mycode.....
    }
}

// или

@RunOutsideAngularAll
class SomeClass {
    myFunc() {
        mycode.....
    }
}

RunOutsideAngular- in a good way it is necessary to type with a generic for angular.
RunOutsideAngularAll- handles all methods and functions, incl. inherited, can be simplified to work only with methods of the current class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question