Answer the question
In order to leave comments, you need to log in
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.....
}
@RunOutsideAngular
myFunc() {
mycode.....
}
myFunc() {
this.ngZone.runOutsideAngular(() => {
mycode.........
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question