Angular 4 Decorator无法访问类范围

时间:2018-01-11 07:12:15

标签: angular typescript scope real-time decorator

我试图写一个装饰器,它会在给定的间隔后调用一个方法。我们的想法是在不改变基本服务代码中的任何内容的情况下创建实时数据服务。

到目前为止,我已经能够实现以下目标:

装饰员代码:

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/')
}

我无法弄清楚如何在装饰器中使用正确的范围。任何线索都赞赏。

1 个答案:

答案 0 :(得分:1)

target.ngOnDestroy = function () {

应该是

target.ngOnDestroy = () => {