在使用自定义装饰器更新某些数据时,我在订阅方面遇到了问题。
情况是这样的:我有定制的装饰师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是类的原型,而不是实际的组件类实例。
如何解决这个问题?如何取消订阅装潢师订阅?
发布于 2019-03-13 13:55:51
我终于找到了解决办法:
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;
};
}https://stackoverflow.com/questions/55142303
复制相似问题