Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 2定制装饰取消订阅策略_Angular_Rxjs_Decorator - Fatal编程技术网

Angular 2定制装饰取消订阅策略

Angular 2定制装饰取消订阅策略,angular,rxjs,decorator,Angular,Rxjs,Decorator,我在使用自定义装饰程序更新某些数据时遇到订阅问题 情况是这样的: 我有定制的decoratorUserChange。此装饰器是一个方法装饰器,在一些组件中,它用于在用户更改时运行组件方法。 装饰器订阅到用户流中,每当用户更改时,它都会调用该方法: 例如: 装饰师: export function UserChange(updater: UserUpdater) { return function (target: any, propertyKey: string, descriptor: P

我在使用自定义装饰程序更新某些数据时遇到订阅问题

情况是这样的: 我有定制的decorator
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;
  };
}