fix(common): properly cast http param values to strings (#42643)

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
This commit is contained in:
cexbrayat
2021-06-24 14:27:31 +02:00
committed by Dylan Hunn
parent a2d5358c9b
commit 10691c626b
2 changed files with 11 additions and 1 deletions
+3 -1
View File
@@ -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;
+8
View File
@@ -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}});