fix(router): fix `serializeQueryParams` logic (#42481)

corrects a bug that resulted in query params such as
`[queryParams]={a: 1, b:[]}` being serialized as 'a=1&'
instead of 'a=1'

resolves #42445

PR Close #42481
This commit is contained in:
Sam Severance 2021-06-04 13:25:24 -04:00 committed by Jessica Janiuk
parent 171428ec98
commit c44ab4f6da
2 changed files with 19 additions and 6 deletions

View File

@ -497,12 +497,15 @@ function serializeMatrixParams(params: {[key: string]: string}): string {
}
function serializeQueryParams(params: {[key: string]: any}): string {
const strParams: string[] = Object.keys(params).map((name) => {
const value = params[name];
return Array.isArray(value) ?
value.map(v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') :
`${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
});
const strParams: string[] =
Object.keys(params)
.map((name) => {
const value = params[name];
return Array.isArray(value) ?
value.map(v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') :
`${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
})
.filter(s => !!s);
return strParams.length ? `?${strParams.join('&')}` : '';
}

View File

@ -27,6 +27,16 @@ describe('createUrlTree', () => {
expect(serializer.serialize(t2)).toEqual('/a/c/c2?m=v1&m=v2');
});
it('should support parameter with empty arrays as values', () => {
const p1 = serializer.parse('/a/c');
const t1 = create(p1.root.children[PRIMARY_OUTLET], 1, p1, ['c2'], {m: []});
expect(serializer.serialize(t1)).toEqual('/a/c/c2');
const p2 = serializer.parse('/a/c');
const t2 = create(p2.root.children[PRIMARY_OUTLET], 1, p2, ['c2'], {m: [], n: 1});
expect(serializer.serialize(t2)).toEqual('/a/c/c2?n=1');
});
it('should set query params', () => {
const p = serializer.parse('/');
const t = createRoot(p, [], {a: 'hey'});