How to escape angular HttpParams?

Angular 13 still has this problem. Look at https://github.com/angular/angular/issues/11058 and https://github.com/angular/angular/pull/45111
The solution that worked for me was written by Ali Kamalizade at https://betterprogramming.pub/how-to-fix-angular-httpclient-not-escaping-url-parameters-ddce3f9b8746
The following is his solution. The same solution was suggested by Noémi Salaün in the accepted answer of this question.

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

You can use it when you create a HttpParams.

 new HttpParams({ encoder: new CustomHttpParamEncoder() })

EDIT: This was fixed in version 14. See https://github.com/angular/angular/blob/main/CHANGELOG.md#http-1 https://blog.angular.io/angular-v14-is-now-available-391a6db736af


As you can see in the source code common/http/src/params.ts, HttpParams uses a default encoder HttpUrlEncodingCodec.

HttpUrlEncodingCodec uses the native encodeURIComponent function but then un-encodes some symbole to meet the RFC specification (not followed by the native JS implementation).

So if you want to keep your + symbol encoded you can encode it manually before using HttpParams, or you can override the HttpParameterCodec with your own implementation and pass it through the HttpParamOptions.encoder attribute.

All this was better explained in the now deprecated Http service. With its UrlSearchParams and the QueryEncoder.

As you can see in the source code http/src/url_search_params.ts

By default, QueryEncoder encodes keys and values of parameters using encodeURIComponent, and then un-encodes certain characters that are allowed to be part of the query according to IETF RFC 3986: https://www.rfc-editor.org/rfc/rfc3986.

These are the characters that are not encoded: ! $ \' ( ) * + , ; A 9 - . _ ~ ? /

If the set of allowed query characters is not acceptable for a particular backend, QueryEncoder can be subclassed and provided as the 2nd argument to URLSearchParams.

Tags:

Http

Angular