angular 9打造用户系统 - 7使用ngrx router store管理路由

楚天乐 483 0 条

本篇要做什么

本系列最后一篇
本文将使用ngrx router store来绑定angular路由到ngrx,同事使用CustomRouteStateSerializer

github代码:https://github.com/shyandsy/angular-9-ngrx-user-mamagement

原教程视频连接

安装文档文档位置

https://github.com/ngrx/platform/tree/master/docs/router-store

安装

npm install @ngrx/router-store --save

新建src\app\shared\utils.ts, customer-route-state-serializer。这段代码是上面文档提供的

import { StoreModule, ActionReducerMap } from "@ngrx/store";
import { Params, RouterStateSnapshot} from '@angular/router';
import { RouterStateSerializer, RouterReducerState, routerReducer, } from '@ngrx/router-store';

export interface RouterStateUrl {
  url: string;
  params: Params;
  queryParams: Params;
}

export interface State {
    router: RouterReducerState<RouterStateUrl>;
  }

export class CustomSerializer implements RouterStateSerializer<RouterStateUrl> {
  serialize(routerState: RouterStateSnapshot): RouterStateUrl {
    let route = routerState.root;

    while (route.firstChild) {
      route = route.firstChild;
    }

    const {
      url,
      root: { queryParams },
    } = routerState;
    const { params } = route;

    // Only return an object including the URL, params and query params
    // instead of the entire snapshot
    return { url, params, queryParams };
  }
}

// In your root reducer
export const reducers: ActionReducerMap<State> = {
  router: routerReducer,
};

步骤

  1. 修改src\app\app.module.ts
import { StoreRouterConnectingModule, routerReducer, RouterStateSerializer} from '@ngrx/router-store';
import { CustomSerializer } from "./shared/utils"

 imports: [
    BrowserModule,
    StoreModule.forRoot({}), // 在module中添加reducer
    StoreDevtoolsModule.instrument(),
    EffectsModule.forRoot([]),
    HttpClientModule,
    AppRoutingModule,
    ReactiveFormsModule,    // 使用FormBuilder需要导入ReactiveFormsModule

    // 增加
    StoreRouterConnectingModule.forRoot({stateKey: "router"}),
  ],
  // 加入provider
  providers: [{ provide: RouterStateSerializer, useClass: CustomSerializer }], 

效果

11.png
12.png



发表我的评论
昵称 (必填)
邮箱 (必填)
网址
执行时间: 48.538208007812 毫秒