From 10691c626bf381bedfa278e9d50ab922b4b656cd Mon Sep 17 00:00:00 2001 From: cexbrayat Date: Thu, 24 Jun 2021 14:27:31 +0200 Subject: [PATCH] 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 --- packages/common/http/src/params.ts | 4 +++- packages/common/http/test/params_spec.ts | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/common/http/src/params.ts b/packages/common/http/src/params.ts index 13e68cf2eee..d82bfcfd86b 100644 --- a/packages/common/http/src/params.ts +++ b/packages/common/http/src/params.ts @@ -164,7 +164,9 @@ export class HttpParams { this.map = new Map(); 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; diff --git a/packages/common/http/test/params_spec.ts b/packages/common/http/test/params_spec.ts index 2a1ae1deb57..9e7495d638b 100644 --- a/packages/common/http/test/params_spec.ts +++ b/packages/common/http/test/params_spec.ts @@ -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}});