【问题标题】:Angular 2 custom decorator unsubscription strategyAngular 2 自定义装饰器退订策略
【发布时间】:2019-08-04 03:42:33
【问题描述】:

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

情况是这样的: 我有自定义装饰器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是类的原型,而不是实际的组件类实例。

如何解决这个问题?如何取消订阅装饰器?

【问题讨论】:

标签: angular rxjs decorator


【解决方案1】:

嗯,我终于找到了解决办法:

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;
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2018-07-30
    • 2017-03-15
    • 2014-12-12
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多