Skip to content

Commit 10691c6

Browse files
cexbrayatdylhunn
authored andcommitted
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
1 parent a2d5358 commit 10691c6

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

packages/common/http/src/params.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,9 @@ export class HttpParams {
164164
this.map = new Map<string, string[]>();
165165
Object.keys(options.fromObject).forEach(key => {
166166
const value = (options.fromObject as any)[key];
167-
this.map!.set(key, Array.isArray(value) ? value : [value]);
167+
// convert the values to strings
168+
const values = Array.isArray(value) ? value.map(valueToString) : [valueToString(value)];
169+
this.map!.set(key, values);
168170
});
169171
} else {
170172
this.map = null;

packages/common/http/test/params_spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,18 +195,26 @@ import {HttpParams} from '@angular/common/http/src/params';
195195
it('should stringify number params', () => {
196196
const body = new HttpParams({fromObject: {a: '', b: 2, c: 3}});
197197
expect(body.toString()).toBe('a=&b=2&c=3');
198+
// make sure the param value is now a string
199+
expect(body.get('b')).toBe('2');
198200
});
199201
it('should stringify number array params', () => {
200202
const body = new HttpParams({fromObject: {a: '', b: [21, 22], c: 3}});
201203
expect(body.toString()).toBe('a=&b=21&b=22&c=3');
204+
// make sure the param values are now strings
205+
expect(body.getAll('b')).toEqual(['21', '22']);
202206
});
203207
it('should stringify boolean params', () => {
204208
const body = new HttpParams({fromObject: {a: '', b: true, c: 3}});
205209
expect(body.toString()).toBe('a=&b=true&c=3');
210+
// make sure the param value is now a boolean
211+
expect(body.get('b')).toBe('true');
206212
});
207213
it('should stringify boolean array params', () => {
208214
const body = new HttpParams({fromObject: {a: '', b: [true, false], c: 3}});
209215
expect(body.toString()).toBe('a=&b=true&b=false&c=3');
216+
// make sure the param values are now booleans
217+
expect(body.getAll('b')).toEqual(['true', 'false']);
210218
});
211219
it('should stringify array params of different types', () => {
212220
const body = new HttpParams({fromObject: {a: ['', false, 3] as const}});

0 commit comments

Comments
 (0)