Skip to content

Commit 6c76c91

Browse files
atscottthePunderWoman
authored andcommitted
feat(router): Add defaultQueryParamsHandling to router configuration (#57198)
This commit adds an option to specify the default value for `queryParamsHandling` in `Router.createUrlTree` when another option is not specified (or is `null|undefined`). resolves #12664 PR Close #57198
1 parent 2a915d1 commit 6c76c91

5 files changed

Lines changed: 62 additions & 6 deletions

File tree

‎goldens/public-api/router/index.api.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,7 @@ export function provideRouter(routes: Routes, ...features: RouterFeatures[]): En
587587
export function provideRoutes(routes: Routes): Provider[];
588588

589589
// @public
590-
export type QueryParamsHandling = 'merge' | 'preserve' | '';
590+
export type QueryParamsHandling = 'merge' | 'preserve' | 'replace' | '';
591591

592592
// @public
593593
export class RedirectCommand {
@@ -744,6 +744,7 @@ export const ROUTER_INITIALIZER: InjectionToken<(compRef: ComponentRef<any>) =>
744744
// @public
745745
export interface RouterConfigOptions {
746746
canceledNavigationResolution?: 'replace' | 'computed';
747+
defaultQueryParamsHandling?: QueryParamsHandling;
747748
onSameUrlNavigation?: OnSameUrlNavigation;
748749
paramsInheritanceStrategy?: 'emptyOnly' | 'always';
749750
resolveNavigationPromiseOnError?: boolean;

‎packages/router/src/models.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,13 +275,14 @@ export type LoadChildren = LoadChildrenCallback;
275275
* One of:
276276
* - `"merge"` : Merge new parameters with current parameters.
277277
* - `"preserve"` : Preserve current parameters.
278-
* - `""` : Replace current parameters with new parameters. This is the default behavior.
278+
* - `"replace"` : Replace current parameters with new parameters. This is the default behavior.
279+
* - `""` : For legacy reasons, the same as `'replace'`.
279280
*
280281
* @see {@link UrlCreationOptions#queryParamsHandling}
281282
* @see {@link RouterLink}
282283
* @publicApi
283284
*/
284-
export type QueryParamsHandling = 'merge' | 'preserve' | '';
285+
export type QueryParamsHandling = 'merge' | 'preserve' | 'replace' | '';
285286

286287
/**
287288
* The type for the function that can be used to handle redirects when the path matches a `Route` config.

‎packages/router/src/router.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ export class Router {
452452
navigationExtras;
453453
const f = preserveFragment ? this.currentUrlTree.fragment : fragment;
454454
let q: Params | null = null;
455-
switch (queryParamsHandling) {
455+
switch (queryParamsHandling ?? this.options.defaultQueryParamsHandling) {
456456
case 'merge':
457457
q = {...this.currentUrlTree.queryParams, ...queryParams};
458458
break;

‎packages/router/src/router_config.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import {InjectionToken} from '@angular/core';
1010

11-
import {OnSameUrlNavigation} from './models';
11+
import {OnSameUrlNavigation, QueryParamsHandling} from './models';
1212

1313
/**
1414
* Error handler that is invoked when a navigation error occurs.
@@ -113,6 +113,20 @@ export interface RouterConfigOptions {
113113
*/
114114
urlUpdateStrategy?: 'deferred' | 'eager';
115115

116+
/**
117+
* The default strategy to use for handling query params in `Router.createUrlTree` when one is not provided.
118+
*
119+
* The `createUrlTree` method is used internally by `Router.navigate` and `RouterLink`.
120+
* Note that `QueryParamsHandling` does not apply to `Router.navigateByUrl`.
121+
*
122+
* When neither the default nor the queryParamsHandling option is specified in the call to `createUrlTree`,
123+
* the current parameters will be replaced by new parameters.
124+
*
125+
* @see {@link Router#createUrlTree}
126+
* @see {@link QueryParamsHandling}
127+
*/
128+
defaultQueryParamsHandling?: QueryParamsHandling;
129+
116130
/**
117131
* When `true`, the `Promise` will instead resolve with `false`, as it does with other failed
118132
* navigations (for example, when guards are rejected).

‎packages/router/test/create_url_tree.spec.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@ import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'
1111
import {By} from '@angular/platform-browser';
1212

1313
import {createUrlTreeFromSnapshot} from '../src/create_url_tree';
14-
import {Routes} from '../src/models';
14+
import {QueryParamsHandling, Routes} from '../src/models';
1515
import {Router} from '../src/router';
1616
import {RouterModule} from '../src/router_module';
1717
import {ActivatedRoute, ActivatedRouteSnapshot} from '../src/router_state';
1818
import {Params, PRIMARY_OUTLET} from '../src/shared';
1919
import {DefaultUrlSerializer, UrlTree} from '../src/url_tree';
20+
import {provideRouter, withRouterConfig} from '../src';
2021

2122
describe('createUrlTree', async () => {
2223
const serializer = new DefaultUrlSerializer();
@@ -574,6 +575,45 @@ describe('createUrlTree', async () => {
574575
});
575576
});
576577

578+
describe('defaultQueryParamsHandling', () => {
579+
async function setupRouter(defaultQueryParamsHandling: QueryParamsHandling): Promise<Router> {
580+
TestBed.configureTestingModule({
581+
providers: [
582+
provideRouter(
583+
[{path: '**', component: class {}}],
584+
withRouterConfig({
585+
defaultQueryParamsHandling,
586+
}),
587+
),
588+
],
589+
});
590+
591+
const router = TestBed.inject(Router);
592+
await router.navigateByUrl('/initial?a=1');
593+
return router;
594+
}
595+
596+
it('can use "merge" as the default', async () => {
597+
const router = await setupRouter('merge');
598+
await router.navigate(['new'], {queryParams: {'b': 2}});
599+
expect(router.url).toEqual('/new?a=1&b=2');
600+
});
601+
602+
it('can use "perserve" as the default', async () => {
603+
const router = await setupRouter('preserve');
604+
await router.navigate(['new'], {queryParams: {'b': 2}});
605+
expect(router.url).toEqual('/new?a=1');
606+
});
607+
608+
it('can override the default by providing a new option', async () => {
609+
const router = await setupRouter('preserve');
610+
await router.navigate(['new'], {queryParams: {'b': 2}, queryParamsHandling: 'merge'});
611+
expect(router.url).toEqual('/new?a=1&b=2');
612+
await router.navigate(['replace'], {queryParamsHandling: 'replace'});
613+
expect(router.url).toEqual('/replace');
614+
});
615+
});
616+
577617
async function createRoot(
578618
tree: UrlTree,
579619
commands: any[],

0 commit comments

Comments
 (0)