Skip to content

Commit

Permalink
fix(common): properly cast http param values to strings (#42643)
Browse files Browse the repository at this point in the history
Before this commit, when initializing `HttpParams` with:

    const body = new HttpParams({fromObject: {b: 2}});

then `body.get('b')` returned `2` instead of `'2'` as expected.

This commit makes sure the values are converted to strings in such cases.

Fixes #42641

PR Close #42643
  • Loading branch information
cexbrayat authored and dylhunn committed May 4, 2022
1 parent a2d5358 commit 10691c6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/common/http/src/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,9 @@ export class HttpParams {
this.map = new Map<string, string[]>();
Object.keys(options.fromObject).forEach(key => {
const value = (options.fromObject as any)[key];
this.map!.set(key, Array.isArray(value) ? value : [value]);
// convert the values to strings
const values = Array.isArray(value) ? value.map(valueToString) : [valueToString(value)];
this.map!.set(key, values);
});
} else {
this.map = null;
Expand Down
8 changes: 8 additions & 0 deletions packages/common/http/test/params_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,18 +195,26 @@ import {HttpParams} from '@angular/common/http/src/params';
it('should stringify number params', () => {
const body = new HttpParams({fromObject: {a: '', b: 2, c: 3}});
expect(body.toString()).toBe('a=&b=2&c=3');
// make sure the param value is now a string
expect(body.get('b')).toBe('2');
});
it('should stringify number array params', () => {
const body = new HttpParams({fromObject: {a: '', b: [21, 22], c: 3}});
expect(body.toString()).toBe('a=&b=21&b=22&c=3');
// make sure the param values are now strings
expect(body.getAll('b')).toEqual(['21', '22']);
});
it('should stringify boolean params', () => {
const body = new HttpParams({fromObject: {a: '', b: true, c: 3}});
expect(body.toString()).toBe('a=&b=true&c=3');
// make sure the param value is now a boolean
expect(body.get('b')).toBe('true');
});
it('should stringify boolean array params', () => {
const body = new HttpParams({fromObject: {a: '', b: [true, false], c: 3}});
expect(body.toString()).toBe('a=&b=true&b=false&c=3');
// make sure the param values are now booleans
expect(body.getAll('b')).toEqual(['true', 'false']);
});
it('should stringify array params of different types', () => {
const body = new HttpParams({fromObject: {a: ['', false, 3] as const}});
Expand Down

0 comments on commit 10691c6

Please sign in to comment.