使用redirectTo在Angular RoutingModule中重定向时如何维护查询参数?

问题描述 投票:0回答:1

总结

我想将我的 Angular

RoutingModule
从一个路径重定向到另一个路径,同时维护查询参数。但是,当重定向完成时,查询参数将不再存在。

这里的用例是,我们提供深层链接的 UI 应该具有以特定路径开头的深层链接:

/views
。但是,显示的组件属于单独的 Angular 模块,因此我想重定向到各个模块中的页面。

示例

深层链接 应该重定向到 但重定向到
/views/createNewFoo?type=a&date=2024-01-01
/foo/create?type=a&date=2024-01-01
/foo/create

路线配置

{
  path: 'views',
  pathMatch: 'prefix',
  children: [
    {
      path: 'createNewFoo',
      redirectTo: '/foo/create'
    }
  ]
}
javascript angular angularjs angular-ui-router angular-routing
1个回答
0
投票

我用
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 });
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.