如何正确使用NGRX路由器?

How to use NGRX Routers correctly?

老实说,我完全被文档弄糊涂了,此外我还想知道以下内容:

If I use the NGRX Router, will I need to use the angular's native app-rounting? If so, how do I integrate the NGRX Router with the <router-outlet>?

你能给我一个简单的例子吗?

Angular路由器和NGRX路由器协同工作。 Angular 路由器负责应用程序中的实际路由,NGRX 路由器负责从 Angular 路由器中获取信息,以下是在没有 NGRX 的情况下使用导航的简单示例。

@Injectable()
export class SomeComponent {
  constructor(private router: Router) {}
  /*
  Your Component code  
  */
  onSubmit() {
    this.router.navigate(['/some-url'])
  }

}

按照 NGRX Router documentation 设置商店。

以下是在 NGRX

中使用 Angular 路由的方法

router.action.ts(从组件发送操作以进行导航)

import { createAction, props } from '@ngrx/store';
import { NavigationExtras } from '@angular/router';

export enum RouterActionTypes {
  Go = '[Router] Go',
  Back = '[Router] Back'
}

export const Go = createAction(RouterActionTypes.Go, props<{ payload: { path: any[]; query?: object; extras?: NavigationExtras } }>());

export const Back = createAction(RouterActionTypes.Back);

router.effect.ts(效果处理副作用,它捕获来自组件的导航动作分派并进行实际路由)

import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { tap, map } from 'rxjs/operators';
import * as RouterActions from '../actions/router.actions';

@Injectable()
export class RouterEffects {
  constructor(private actions$: Actions, private router: Router, private location: Location) {}

  navigate$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(RouterActions.Go),
        map((action) => action.payload),
        tap(({ path, query: queryParams, extras }) => {
          this.router.navigate(path, { queryParams, ...extras });
        }),
      ),
    { dispatch: false },
  );

  navigateBack$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(RouterActions.Back),
        tap(() => this.location.back()),
      ),
    { dispatch: false },
  );
}

NGRX 提供内置 Selectors 来获取路由信息,例如 queryParams,url 等

例如,您必须按部门获取用户列表,而 departmentId 在 URL

的查询参数中
https://localhost:4200/users?deparmentId=4

读取查询参数的正确方法是通过 selectQueryParams NGRX 库提供的选择器

export const selectSelectedDepatmentId = selectQueryParam('deparmentId');

export const selectUsersByDepartment = createSelector(
   selectUsers,
   selectSelectedDepatmentId,
   (users, departmentId) => users.filter(u => u.departmentId === departmentId)
);