【发布时间】:2018-06-20 11:02:58
【问题描述】:
我正在尝试编写一个装饰器,它将在给定的时间间隔后调用一个方法。这个想法是在不更改基本服务代码中的任何内容的情况下制作实时数据服务。
到目前为止,我已经能够实现以下目标:
装饰器代码:
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/')
}
我无法弄清楚如何在装饰器中使用正确的范围。任何线索表示赞赏。
【问题讨论】:
-
您能否编辑您的问题以包含您注入服务的代码?
-
更新问题
-
你能展示服务本身吗?
-
更新问题
标签: angular typescript scope real-time decorator