Skip to content

Commit

Permalink
fix(http): honor RequestArgs.search and RequestArgs.params map type
Browse files Browse the repository at this point in the history
Currently `new Request({search: ...})` is not honored, and
`new Request({params: {'x': 'y'}) doesn't work either, as this object would have
toString() called. This change allows both of these cases to work, as proved by
the 2 new tests.

Fixes angular#15761
  • Loading branch information
alxhub committed May 3, 2017
1 parent 9684d78 commit f8c9b45
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
23 changes: 21 additions & 2 deletions packages/http/src/static_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,14 @@ export class Request extends Body {
// TODO: assert that url is present
const url = requestOptions.url;
this.url = requestOptions.url !;
if (requestOptions.params) {
const params = requestOptions.params.toString();
const paramsArg = requestOptions.params || requestOptions.search;
if (paramsArg) {
let params: string;
if (typeof paramsArg === 'object' && !(paramsArg instanceof URLSearchParams)) {
params = urlEncodeParams(paramsArg).toString();
} else {
params = paramsArg.toString();
}
if (params.length > 0) {
let prefix = '?';
if (this.url.indexOf('?') != -1) {
Expand Down Expand Up @@ -163,6 +169,19 @@ export class Request extends Body {
}
}

function urlEncodeParams(params: {[key: string]: any}): URLSearchParams {
const searchParams = new URLSearchParams();
Object.keys(params).forEach(key => {
const value = params[key];
if (value && Array.isArray(value)) {
value.forEach(element => searchParams.append(key, element.toString()));
} else {
searchParams.append(key, value.toString());
}
});
return searchParams;
}

const noop = function() {};
const w = typeof window == 'object' ? window : noop;
const FormData = (w as any /** TODO #9100 */)['FormData'] || noop;
Expand Down
10 changes: 10 additions & 0 deletions packages/http/test/static_request_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,15 @@ export function main() {

expect(req.text()).toEqual('');
});

it('should use object params', () => {
const req = new Request({url: 'http://test.com', params: {'a': 3, 'b': ['x', 'y']}});
expect(req.url).toBe('http://test.com?a=3&b=x&b=y');
});

it('should use search if present', () => {
const req = new Request({url: 'http://test.com', search: 'a=1&b=2'});
expect(req.url).toBe('http://test.com?a=1&b=2');
})
});
}

0 comments on commit f8c9b45

Please sign in to comment.