我有一个带有 Angular 前端的大型复杂应用程序。在前端,我有几个延迟加载的模块。
我的一个功能级 NgRx 存储需要由另一个功能使用。这两个功能都是延迟加载的。唯一的共同父级是应用程序的根级别,我希望最大限度地减少额外的文件和代码。
我将第一个功能的 NgRx 存储文件提取到它们自己的模块中,并将该模块导入到该功能中。这很好用。我还尝试将该模块导入到其他功能中 - 这就是事情崩溃的地方。
第二个功能成功加载*.reducer.ts文件,但未加载相关*.effects.ts文件。因此,当第二个功能分派动作时,没有加载效果来作用于该动作。
如果在第二个功能之前访问第一个功能,则效果将被加载并按预期工作。当第二个功能在第一个功能之前加载和使用时,就会出现问题。
无论先访问哪个功能,如何使效果文件正确加载到这两个功能中?
标识符更改/删除,稍微简化
共同影响:
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, concatMap, map } from 'rxjs/operators';
import * as MySharedActionsfrom './mySharedActions.actions';
import { AService} from './services/AService';
@Injectable()
export class MySharedEffects {
mySharedEffect$ = createEffect(() =>
this.actions$.pipe(
ofType(MySharedActions.actionOne),
concatMap(action => {
return this.aService.aMethod(action.prop1, action.prop2).pipe(
map(data=> {
if (data.succeeded) {
return MySharedActions.actionOneSuccess({ data});
} else {
return MySharedActions.actionOneFailure({ error: data});
}
}),
catchError(error => of(MySharedActions.actionOneFailure({ error }))),
);
}),
),
);
constructor(
private actions$: Actions,
private readonly aService: AService,
) {}
}
Run Code Online (Sandbox Code Playgroud)
共享商店模块
import { NgModule } from '@angular/core';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { MySharedEffects } from './myShared.effects';
import * as fromMyShared from './myShared.reducer';
@NgModule({
imports: [
EffectsModule.forFeature([ MySharedEffects ]),
StoreModule.forFeature(fromMyShared.mySharedFeatureKey, MySharedEffects.reducer),
// ...
],
})
export class MySharedModule {}
Run Code Online (Sandbox Code Playgroud)
第一个功能模块(一切正常)
import { NgModule } from '@angular/core';
// ...
import { MySharedModule } from './store/myShared.module';
@NgModule({
entryComponents: [/*...*/],
imports: [
// ...,
MySharedModule ,
// ...,
],
providers: [/*...*/],
})
export class FirstFeatureModule {}
Run Code Online (Sandbox Code Playgroud)
第二个功能模块(效果未加载)
// ...
import { NgModule } from '@angular/core';
import { MySharedModule } from '../../../first-feature/store/myShared.module';
@NgModule({
declarations: [/*...*/],
entryComponents: [/*...*/],
imports: [/*...*/, MySharedModule , /*...*/],
exports: [/*...*/],
})
export class SecondFeatureModule{}
Run Code Online (Sandbox Code Playgroud)
您的代码示例应该可以工作。您是否已将商店正确注入到第二个功能模块组件中?如果您没有正确注入商店,则无法在该部分上调度操作,因此您的效果将不会触发。
例子:
在进口方面:
import * as fromApprovals from '../state/reducers';
import * as fromAuth from '../../auth/state/reducers';
import * as fromData from '../../data/state/reducers';
Run Code Online (Sandbox Code Playgroud)
在构造函数中:
// combine your stores this way, should the second feature have it's own part of a store
constructor(private store: Store<fromApprovals.State & fromAuth.State & fromData.State>,'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3990 次 |
| 最近记录: |