From fcfce99e9ee9c5ffd2a637ae5f74254c632a2d03 Mon Sep 17 00:00:00 2001 From: cexbrayat Date: Wed, 22 Jan 2020 09:05:37 +0100 Subject: [PATCH] fix(common): remove extra & in http params (#34896) Previous to this commit, HTTP params like `{ a: '1', b: [], c: '3' }` resulted in a request like `a=1&&c=3` (note the double &&). The ideal fix would probably be to stringify these params to `a=1&b=&c=3` like we do for empty string values. But that might be breaking as some APIs may rely on the absence of the parameter. This fixes the issue in a compatible way by just removing the extra and unnecessary `&`, resulting in `a=1&c=3`. PR Close #34896 --- packages/common/http/src/params.ts | 6 ++++++ packages/common/http/test/params_spec.ts | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/packages/common/http/src/params.ts b/packages/common/http/src/params.ts index d43d91adbd..30caa33cde 100755 --- a/packages/common/http/src/params.ts +++ b/packages/common/http/src/params.ts @@ -224,9 +224,15 @@ export class HttpParams { return this.keys() .map(key => { const eKey = this.encoder.encodeKey(key); + // `a: ['1']` produces `'a=1'` + // `b: []` produces `''` + // `c: ['1', '2']` produces `'c=1&c=2'` return this.map !.get(key) !.map(value => eKey + '=' + this.encoder.encodeValue(value)) .join('&'); }) + // filter out empty values because `b: []` produces `''` + // which results in `a=1&&c=1&c=2` instead of `a=1&c=1&c=2` if we don't + .filter(param => param !== '') .join('&'); } diff --git a/packages/common/http/test/params_spec.ts b/packages/common/http/test/params_spec.ts index 669959c851..9c99771043 100644 --- a/packages/common/http/test/params_spec.ts +++ b/packages/common/http/test/params_spec.ts @@ -76,5 +76,20 @@ import {HttpParams} from '@angular/common/http/src/params'; expect(body.keys()).toEqual(['a', 'b', 'c', 'd']); }); }); + + describe('toString', () => { + it('should stringify string params', () => { + const body = new HttpParams({fromObject: {a: '', b: '2', c: '3'}}); + expect(body.toString()).toBe('a=&b=2&c=3'); + }); + it('should stringify array params', () => { + const body = new HttpParams({fromObject: {a: '', b: ['21', '22'], c: '3'}}); + expect(body.toString()).toBe('a=&b=21&b=22&c=3'); + }); + it('should stringify empty array params', () => { + const body = new HttpParams({fromObject: {a: '', b: [], c: '3'}}); + expect(body.toString()).toBe('a=&c=3'); + }); + }); }); }