我试图写一个装饰器,在给定的间隔之后调用一个方法。其思想是在不改变基类服务代码中任何内容的情况下进行实时数据服务。
到目前为止,我已经能够做到以下几点:
装饰器代码:

export const ON_DESTROY_SYMBOL = Symbol();

export function repeat(): MethodDecorator {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        // get the original method reference
        const originalMethod = descriptor.value;
        let timer;
        descriptor.value = (...args) => {
        //set a timer to call the method every 3 seconds
        //TODO: make the interval dynamic
            timer = setInterval( () =>  {
                originalMethod.apply(target, args);
            }, 3000);
        };
        target[ON_DESTROY_SYMBOL] = target.ngOnDestroy;
        // Destroy timer on Component destroy
        target.ngOnDestroy = function () {
            this[ON_DESTROY_SYMBOL]();
            clearInterval(timer);
            console.log('Component destroy event successfully handled!');
        };
        return descriptor;
    };
}

使用它:
@repeat()
myMethod() {
    console.log('Logging in console',new Date());
}

这和预期的一样。该方法每3秒重复一次,我可以在控制台中看到日志。
但是当我尝试使用类中的任何服务时,它都会失败并出现错误
Cannot read property 'someService' of undefined
我的目标是能够像这样使用它,
组件代码:
export class PlaygroundComponent implements OnInit, OnDestroy {
    //inject service
    constructor(private someService: SomeService){
    }

    @repeat()
    myMethod() {
        this.someService.fetchData().subscribe(res => //do something with data);
    }
}

服务代码:
@Injectable()
export class SomeService {
constructor(private http: HttpClient) {
}

fetchData() {
    return this.http.get('https://data.com/json/')
}

我不知道如何在decorator中使用正确的作用域。感谢任何线索。

最佳答案

target.ngOnDestroy = function () {

应该是
target.ngOnDestroy = () => {

关于angular - Angular 4 Decorator无法访问类范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48201602/

10-11 11:37