我想将我的 Angular
RoutingModule
从一个路径重定向到另一个路径,同时维护查询参数。但是,当重定向完成时,查询参数将不再存在。
这里的用例是,我们提供深层链接的 UI 应该具有以特定路径开头的深层链接:
/views
。但是,显示的组件属于单独的 Angular 模块,因此我想重定向到各个模块中的页面。
深层链接 | 应该重定向到 | 但重定向到 |
---|---|---|
|
|
|
{
path: 'views',
pathMatch: 'prefix',
children: [
{
path: 'createNewFoo',
redirectTo: '/foo/create'
}
]
}
CanActivateFn
解决了它:import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { from } from 'rxjs';
export const redirectWhileKeepingQueryParams =
(redirectTo: string): CanActivateFn =>
route =>
from(inject(Router).navigate([redirectTo], { queryParams: route.queryParams }));
{
path: 'views',
pathMatch: 'prefix',
children: [
{
path: 'createNewFoo',
canActivate: [redirectWhileKeepingQueryParams('/foo/create')],
children: []
}
]
}
CanActivateFn
:import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot } from '@angular/router';
import { redirectWhileKeepingQueryParams } from './redirect-while-keeping-query-params';
const redirectTo = '/foo/create';
describe('redirectWhileKeepingQueryParams', () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => redirectWhileKeepingQueryParams(redirectTo)(...guardParameters));
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => expect(executeGuard).toBeTruthy());
it('should redirect to the given route', () => {
// Arrange
const navigateSpy = jest.spyOn(TestBed.inject(Router), 'navigate');
const route = { queryParams: { key1: 'value', key2: 123 } } as Partial<ActivatedRouteSnapshot> as ActivatedRouteSnapshot;
const state = {} as RouterStateSnapshot;
// Act
executeGuard(route, state);
// Assert
expect(navigateSpy).toHaveBeenCalledWith([redirectTo], { queryParams: route.queryParams });
});
});