使用
ngrx
,让您的商店也处理路由器状态,保留
范式然后,您只需在效果中调度一个路由器操作,以响应您的成功操作。
这还有一个额外的好处,就是能够
time travel
'路由以及应用程序状态的其余部分。
implementation of router-store integration
随时可用。
你可以这样做(只是一个指导方针,增强你的需求):
应用程序。单元
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 { }
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'));
使用具有最新功能的NGRX v8+进行更新:
应用程序模块
:
import { StoreRouterConnectingModule, routerReducer } from '@ngrx/router-store';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
StoreModule.forRoot({ routerReducer }),
RouterModule.forRoot([
// ...
{ path: 'task-list', component: TaskListComponent },
{ path: 'error-page', component: ErrorPageComponent }
]),
StoreRouterConnectingModule.forRoot(),
],
bootstrap: [AppComponent],
})
export class AppModule {}
任务效果
:
@Injectable()
export class TaskEffects {
readonly addTaskSuccess$ = createEffect(() =>
this.actions$.pipe(
ofType(LeadAction.ADD_TASK_SUCCESS),
tap(() => this.router.navigate(['task-list'])),
),
{ dispatch: false },
);
readonly addTaskFailure$ = createEffect(() =>
this.actions$.pipe(
ofType(LeadAction.ADD_TASK_FAILURE),
tap(() => this.router.navigate(['error-page'])),
),
{ dispatch: false },
);
constructor(
private readonly actions$: Actions,
private readonly router: Router,
) {}
}