为什么Ngrx-Effects没有在继承的泛型类中自动订阅

时间:2018-06-22 10:41:47

标签: angular typescript ngrx ngrx-effects

我的情况是我的项目中有几个效果类,这些效果类由通用类扩展。从泛型类继承的所有效果不会自动订阅。相反,我必须手动订阅通用类的构造函数中的effect / observable:

    @Injectable()
    export class GenericEffects<T extends Action, K> {
     action: T;
     constructor(
       TCreator: { new (): T },
      protected actions: Actions,
      protected store: Store<K>,
      protected route: string

      ) {
       this.action = new TCreator();

       --> this.effect1.subscribe(); <---
    }

    @Effect({ dispatch: false })
    effect1 = this.actions.ofType(genericActions.EFFECT_1).pipe(
      withLatestFrom(this.store.select<RouterReducerState>('route')),
      map(([action, routerState]) => routerState.state.url),
      map(url => {
        if (url.indexOf(this.route) !== -1 && url.length === 
          this.route.length + 1) {
        this.store.dispatch(this.action);
      }
    })
  );
}

FeatureEffectsModule:

    @Injectable()
    export class FeatureEffects extends GenericEffects<
      featureActions.WhatEverAction,
      fromFeature.State
     > {
      constructor(
        actions: Actions,
        store: Store<fromFeature.State>,
        private service: FeatureService
      ) {
        super(
          featureActions.WhatEverAction,
          actions,
          store,
          'foo'
        );
      }
    }

我想念什么,或者我必须手动执行此操作的原因是什么?

1 个答案:

答案 0 :(得分:1)

由于效果是在非通用版本中触发的,所以我不会考虑订阅通用版本的基类构造函数。我发现在派生类中重新声明效果是可行的,因此我接受了这种数量的代码重复。在您自己的示例中,我添加了1行:

@Injectable()
export class FeatureEffects extends GenericEffects<
  featureActions.WhatEverAction,
  fromFeature.State
 > {
  constructor(
    actions: Actions,
    store: Store<fromFeature.State>,
    private service: FeatureService
  ) {
    super(
      featureActions.WhatEverAction,
      actions,
      store,
      'foo'
    );
  }

  @Effect()  effect1;      //   <---   like this

}