使用自定义装饰器更新某些数据时,订阅出现问题。
情况是这样的:我有自定义装饰器UserChange
。此装饰器是一个方法装饰器,在一些组件中,用于在用户更改时运行组件方法。
装饰器订阅用户流,每当用户更改时,装饰器便调用该方法:
例:
装饰器:
export function UserChange(updater: UserUpdater) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function () {
const update = updater.userChanges().subscribe(() => {
// @ts-ignore
return originalMethod.apply(this, arguments);
});
return originalMethod.apply(this, arguments);
};
return descriptor;
};
}
在某些组件中使用的示例:
@UserChange(AppModule.userUpdater)
private loadUserData() {
this.api.getUserData.subscribe(...);
}
问题是userChanges.subscription()
在销毁组件时如何在装饰器中取消订阅?
通常,订阅将在ngOnDestroy
某个组件中取消订阅,但是在这个地方,我对装饰器订阅没有影响。同样的情况则相反。我没有引用要对此subscription
进行调用的组件add(update)
。因为target
是类的原型,而不是实际的组件类实例。
如何解决这个问题呢?如何取消订阅装饰器订阅?
好吧,我终于找到了解决方案:
export function UserChange(updater: UserUpdater) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function () {
const update = updater.userChanges().subscribe(() => {
// @ts-ignore
return originalMethod.apply(this, arguments);
});
target['ngOnDestroy'] = () => update.unsubscribe();
return originalMethod.apply(this, arguments);
};
return descriptor;
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句