Better Programming

Advice for programmers.

Follow publication

How To Fix Angular HttpClient Not Escaping URL Parameters

Creating a custom HttpParameterCodec to encode everything

Ali Kamalizade
Better Programming
Published in
2 min readJul 23, 2019

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

  1. Create a class which implements HttpParameterCodec. Alternatively, you could also extend HttpUrlEncodingCodec.
  2. The encodeKey and encodeValue functions need to encode the value. Vanilla JavaScript allows you to use encodeURIComponent.
  3. Use the custom encoder class when creating new HttpParams: new HttpParams({ encoder: new CustomHttpParamEncoder() }). The important part is the usage of encodeURIComponent, 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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ali Kamalizade
Ali Kamalizade

Written by Ali Kamalizade

Co-founder of Sunhat. Posts about software engineering, startups and anything else. 有難うございます。🚀

No responses yet

Write a response