Skip to content

Commit

Permalink
fix(router): add support for query params with mulitple values
Browse files Browse the repository at this point in the history
closes #11373
  • Loading branch information
spacebeers authored and vicb committed Dec 9, 2016
1 parent 4e3d58a commit 440ef02
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
29 changes: 25 additions & 4 deletions modules/@angular/router/src/url_tree.ts
Expand Up @@ -370,9 +370,14 @@ function serializeParams(params: {[key: string]: string}): string {
return pairs(params).map(p => `;${encode(p.first)}=${encode(p.second)}`).join('');
}

function serializeQueryParams(params: {[key: string]: string}): string {
const strs = pairs(params).map(p => `${encode(p.first)}=${encode(p.second)}`);
return strs.length > 0 ? `?${strs.join("&")}` : '';
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 => `${encode(name)}=${encode(v)}`).join('&') :
`${encode(name)}=${encode(value)}`;
});

return strParams.length ? `?${strParams.join("&")}` : '';
}

class Pair<A, B> {
Expand Down Expand Up @@ -534,6 +539,7 @@ class UrlParser {
params[decode(key)] = decode(value);
}

// Parse a single query parameter `name[=value]`
parseQueryParam(params: {[key: string]: any}): void {
const key = matchQueryParams(this.remaining);
if (!key) {
Expand All @@ -549,7 +555,22 @@ class UrlParser {
this.capture(value);
}
}
params[decode(key)] = decode(value);

const decodedKey = decode(key);
const decodedVal = decode(value);

if (params.hasOwnProperty(decodedKey)) {
// Append to existing values
let currentVal = params[decodedKey];
if (!Array.isArray(currentVal)) {
currentVal = [currentVal];
params[decodedKey] = currentVal;
}
currentVal.push(decodedVal);
} else {
// Create a new value
params[decodedKey] = decodedVal;
}
}

parseParens(allowPrimary: boolean): {[key: string]: UrlSegmentGroup} {
Expand Down
5 changes: 5 additions & 0 deletions modules/@angular/router/test/url_serializer.spec.ts
Expand Up @@ -160,6 +160,11 @@ describe('url serializer', () => {
expect(url.serialize(tree)).toEqual('/one?a=');
});

it('should handle multiple query params of the same name into an array', () => {
const tree = url.parse('/one?a=foo&a=bar&a=swaz');
expect(tree.queryParams).toEqual({a: ['foo', 'bar', 'swaz']});
});

it('should parse fragment', () => {
const tree = url.parse('/one#two');
expect(tree.fragment).toEqual('two');
Expand Down

0 comments on commit 440ef02

Please sign in to comment.