gpt4 book ai didi

angular - 在组件的构造函数中分派(dispatch)操作时不会调用 ngrx 效果

转载 作者:行者123 更新时间:2023-12-04 04:19:41 25 4
gpt4 key购买 nike

这是我的应用模块:

@NgModule({
declarations: [
SampleA
],
imports: [
BrowserModule,
EffectsModule.forRoot([APIEffects]),
HttpClientModule,
StoreModule.forRoot(reducers),
StoreDevtoolsModule.instrument({
maxAge: 25, // Retains last 25 states
logOnly: environment.production, // Restrict extension to log-only mode
}),
KeyboardShortcutsModule.forRoot()
],
providers: [
APIService,
{
provide: HTTP_INTERCEPTORS,
useClass: HttpMockRequestInterceptor,
multi: true
}
],
bootstrap: [],
entryComponents: [
SampleComponent
]
})
export class AppModule{...}

这是APIEffect:

@Injectable()
export class APIEffects {
fetchData$ = createEffect(() => this.actions$.pipe(
ofType(Actions.apiFetchData),
mergeMap((action) => this.apiService.fetchData(...action)
.pipe(
map(data => Actions.apiSuccess({ data })),
catchError(() => of(Actions.apiCallFailed()))
)
)
));
}

现在,如果我在 SampleComponent 构造函数中分派(dispatch) apiFetchData 操作,则不会调用效果:

export class SampleComponent {
constructor(private store: Store<{ state: State }>) {
store.dispatch(Actions.apiFetchData(...))
}
}

如果我稍后在组件的生命周期中分派(dispatch)相同的操作,那么一切正常并且效果发生。

Redux DevTools 中,我可以看到 Action 分派(dispatch)发生在 effects init 之前。顺序如下:

@ngrx/store/init
[API] fetch data // this is the fetch data action
@ngrx/effects/init

所以我的问题是如何在构建组件之前强制初始化效果。

更新

我还没有解决上面提到的问题,但是现在,我决定使用ROOT_EFFECTS_INIT,(感谢@mitschmidt 提到它),并在之后派发一系列 Action effects 已准备好初始化我的应用程序的状态。下面是使用 ROOT_EFFECTS_INIT 的效果:

  init$ = createEffect(() =>
this.actions$.pipe(
ofType(ROOT_EFFECTS_INIT),
map(action => CoverageUIActions.apiFetchData({...}))
)
);

最佳答案

为了实现这一点,您可能需要查看 NGRX 生命周期事件,例如此处所述的 ROOT_EFFECTS_INIT:https://ngrx.io/guide/effects/lifecycle

使用 APP_INITIALIZER 注入(inject) token (很好的教程 here )加上必要的语法糖,您可以构建一个应用程序初始化服务,延迟您的应用程序引导,直到 NGRX 根效果被注册(没有组件会在这种情况下进行初始化,构造函数中上面的逻辑应该可以工作)。在最近的一个项目中,我走上了类似的道路:

export class AppInitializer {
constructor(private readonly actions$: Actions) {}

initialize() {
return this.actions$.pipe(ofType(ROOT_EFFECTS_INIT));
}
}
  return (): Promise<any> => {
return appInitializer.initialize().toPromise();
};
}

...最后将提供程序添加到您的模块中:

import { appInitializerFactory } from './app-initializer.factory';

export const APP_INITIALIZER_PROVIDER: Provider = {
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [AppInitializer],
multi: true,
};
// your module...
{
...
providers: [APP_INITIALIZER_PROVIDER]
...
}

关于angular - 在组件的构造函数中分派(dispatch)操作时不会调用 ngrx 效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59670943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com