
How To Fix Angular HttpClient Not Escaping URL Parameters
Creating a custom HttpParameterCodec to encode everything
The Angular Http Client was introduced in Angular 4.3 and works better than the old Http in most ways. It uses JSON as content type automatically, it supports HTTP interceptors, and it has better TypeScript support than the old Http.
Recently, I needed to add query parameters to an HTTP request. For this use case, Angular provides the HttpParams
class. Strangely, I noticed my query parameter was not encoded as expected, which made the API return wrong results.
This behaviour might be confusing: HttpUrlEncodingCodec
does not encode some special characters like +. This is likely to comply with RFC 3986. However, there are cases where you need to encode those characters. In this article, I want to show you how you can do that.
How To Encode HttpParams in Angular
- Create a class which implements
HttpParameterCodec
. Alternatively, you could also extendHttpUrlEncodingCodec
. - The
encodeKey
andencodeValue
functions need to encode the value. Vanilla JavaScript allows you to useencodeURIComponent
. - Use the custom encoder class when creating new
HttpParams
:new HttpParams({ encoder: new CustomHttpParamEncoder() })
. The important part is the usage ofencodeURIComponent
, which is a vanilla JavaScript function to encode a string.
Here’s how a custom decoder could look:
import { HttpParameterCodec } from '@angular/common/http';
export class CustomHttpParamEncoder implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(value: string): string {
return encodeURIComponent(value);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(value: string): string {
return decodeURIComponent(value);
}
}
Conclusion
Thanks for reading this article. While the behaviour of the Http Client may seem surprising at first, it is compliant with the RFC. Luckily, it is easy to change the behaviour to fit your needs. Let me know in the comments if this post helped you.