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
This commit is contained in:
cexbrayat 2020-01-22 09:05:37 +01:00 committed by Misko Hevery
parent 6b710f7ae1
commit fcfce99e9e
2 changed files with 21 additions and 0 deletions

View File

@ -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('&');
}

View File

@ -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');
});
});
});
}