使用ngrx存储时,如何在Angular 2中导航

Sim*_*mon 3 ngrx ngrx-effects angular ngrx-store-4.0

我正在使用ngrx store(4.x)和Angular 4.我使用效果在后端进行CRUD操作,就像下面的示例一样,它在后端API上添加了一个Task.

影响:

  @Effect()
  addTask: Observable<Action> = this.actions$
    .ofType(LeadAction.ADD_TASK)
    .map((action: LeadAction.AddTaskAction) => action.payload)
    .switchMap((task: TaskViewModel) => {
      return this.leadApi.leadAddTask(task.LeadId, task)
        .map((taskResult: TaskViewModel) => {
          return new LeadAction.AddTaskSuccessAction(taskResult);
        })
        .catch((e: any) => of(new LeadAction.AddTaskFailureAction(e)));
    });
Run Code Online (Sandbox Code Playgroud)

TaskEditComponent:

  onSave(): void {
    this.store.dispatch(new AddTaskAction(this.task));

    // **** NAVIGATE TO PAGE TaskListComponent or OverviewComponent ON SUCCESS
    // OR
    // **** NAVGIATE TO PAGE Y ON ERROR
  }
Run Code Online (Sandbox Code Playgroud)

问题:在我的组件中,我需要导航到不同的页面,我现在在努力摆弄这个逻辑?

特别是当我考虑以下场景时,不同组件"调用"TaskEditComponent:

应该导航回TaskListComponent:

OverviewComponent-> TaskListComponent-> TaskEditComponent返回List

应该导航回OverviewComponent:

OverviewComponent-> TaskEditComponent

Hee*_*aaw 5

使用ngrx,让你的商店处理路由器状态也是有意义的,保留redux范例.然后,您只需在效果中调度路由器操作以响应您的成功操作.

这具有额外的好处,即能够" 时间旅行 "路线以及应用状态的其余部分.

幸运的是,已经有一个路由器存储集成的实现可以使用了.

希望这有所帮助 :-)


你可以做这样的事情(只是一个指南,增强你的需求):

app.module

import { StoreRouterConnectingModule, routerReducer } from '@ngrx/router-store';
import { App } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    StoreModule.forRoot({ routerReducer: routerReducer }),
    RouterModule.forRoot([
      // ...
      { path: 'task-list', component: TaskListComponent },
      { path: 'error-page', component: ErrorPageComponent }
    ]),
    StoreRouterConnectingModule
  ],
  bootstrap: [App]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

task.effects

import { go } from '@ngrx/router-store';

@Effect()
addTask: Observable<Action> = this.actions$
  .ofType(LeadAction.ADD_TASK_SUCCESS)
  .map((action: LeadAction.AddTaskSuccessAction) => action.payload)
  .map((payload: any) => go('/task-list')); // use payload to construct route options

@Effect()
addTask: Observable<Action> = this.actions$
  .ofType(LeadAction.ADD_TASK_FAILURE)
  .mapTo(go('/error-page'));
Run Code Online (Sandbox Code Playgroud)

  • 从 v4 开始,router-store 中没有 go,因此您需要通过 do 从效果中调用 router.navigate。 (2认同)