Angular 2定制装饰取消订阅策略
我在使用自定义装饰程序更新某些数据时遇到订阅问题 情况是这样的: 我有定制的decoratorAngular 2定制装饰取消订阅策略,angular,rxjs,decorator,Angular,Rxjs,Decorator,我在使用自定义装饰程序更新某些数据时遇到订阅问题 情况是这样的: 我有定制的decoratorUserChange。此装饰器是一个方法装饰器,在一些组件中,它用于在用户更改时运行组件方法。 装饰器订阅到用户流中,每当用户更改时,它都会调用该方法: 例如: 装饰师: export function UserChange(updater: UserUpdater) { return function (target: any, propertyKey: string, descriptor: P
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(...);
}
问题是当组件被销毁时,如何在decorator中取消订阅userChanges.subscription()
通常订阅将在组件的ngondestory
中取消订阅,但在这里,我对decorator订阅没有影响。
同样的情况恰恰相反。我没有引用组件subscription
来调用add(update)
。因为目标
是类的原型,而不是实际的组件类实例
如何解决这个问题?如何取消decorator订阅?我终于找到了解决方案:
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;
};
}
我终于找到了解决办法:
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;
};
}