【发布时间】:2020-08-27 10:35:05
【问题描述】:
在以前使用 Angular 8 和 9 的应用程序中,我使用的是基于类的操作,而不是操作创建器。这一次,我决定尝试使用动作创建器。但是,我遇到了一个问题:我之前使用this.dataPersistence.navigation(...) 用于基于导航执行的异步方法和成功操作,现在它被包裹在createEffect(() => ...) 中,但它似乎不起作用(无论它是否被包裹)
这是设置,其中大部分是样板:
package.json
"@nrwl/angular": "9.2.4",
...
"@angular/cli": "9.1.0",
"@nrwl/workspace": "9.2.4",
action.ts
export const setActivePanelId = createAction('[Interactions] Set Active Panel ID', props<{ id: string }>());
app.routes
const routes: Routes = [
{
path: '',
component: MessagesContainer
}
];
interactions.effects.ts
onNav$ = createEffect(() =>
this.dataPersistence.navigation(MessagesContainer, {
run: (a: ActivatedRouteSnapshot): Observable<Action> | Action | void => {
//An example callback, no async used yet.
return setActivePanelId({id: a['snapshot'].queryParams.panelId});
},
onError: (a: ActivatedRouteSnapshot, e: any): any => {
console.warn(e);
}
}));
app.module.ts
@NgModule({
declarations: [AppComponent, MessagesContainer],
imports: [
BrowserModule,
ComponentsModule,
RouterModule.forRoot(routes, routingOptions),
EffectsModule.forRoot([]),
NxModule.forRoot(),
StoreRouterConnectingModule.forRoot(),
StoreModule.forRoot({}, { metaReducers: [] }),
StoreDevtoolsModule.instrument({
maxAge: 20,
logOnly: config.environment.production
}),
InteractionsModule
],
bootstrap: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {
}
interactions.module.ts
@NgModule({
imports: [
CommonModule,
StoreModule.forFeature(
fromInteractions.INTERACTIONS_FEATURE_KEY,
fromInteractions.reducer
),
EffectsModule.forFeature([InteractionsEffects]),
StoreModule.forFeature(
fromInteractions.INTERACTIONS_FEATURE_KEY,
fromInteractions.reducer
)
],
providers: [InteractionsFacade]
})
export class InteractionsModule {}
更新: 我也试过了
@Effect() nav$ = createEffect(() =>
this.actions$.pipe(
// listens for the routerNavigation action from @ngrx/router-store
navigation(MessagesContainer, {
run: (activatedRouteSnapshot: ActivatedRouteSnapshot) => {
return setActivePanelId({id: 'async!'});
},
onError: (
activatedRouteSnapshot: ActivatedRouteSnapshot,
error: any
) => {
// we can log and error here and return null
// we can also navigate back
console.warn(error)
return null;
}
})
)
);
【问题讨论】:
-
一个对我有用的直接解决方法是添加一个监视 ngrx 导航的效果。
export const onNav = createAction('@ngrx/router-store/navigated', props<{payload: any}>());它让我可以在导航后访问路由器状态,但它确实需要效果中的逻辑来检查我在哪条路线上。需要创建的动作更少,但必须在效果中完成辨别我在哪条路线上的逻辑。 -
我必须将 package.json 中的所有内容降级到 9.0.2 才能使 datapersistence.navigation 正常工作。
标签: angular ngrx ngrx-effects nrwl nrwl-nx