angular - 为什么 Ngrx-Effects 不能在继承的泛型类中自动订阅
问题描述
我有一个案例,我的项目中有几个效果类,它们由一个通用类扩展。从泛型类继承的所有效果都不会自动订阅。相反,我必须手动订阅泛型类的构造函数中的效果/可观察:
@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);
}
})
);
}
功能效果模块:
@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 行:
@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
}