Encode HttpParams Angular - quan1997ap/angular-app-note GitHub Wiki

Một số kí tự khi sử dụng HttpParams sẽ bị encode :

    + thành  khoảng trắng
    | thành  %7C
    @ thành  %40   
    : thành  %3A
    $ thành  %24
    , thành  %2C
    ; thành  %3B
    + thành  %2B
    = thành  %3D
    / thành  %2F

Thông thường khi chúng ta dùng muốn thêm Query Params vào url. Url muong muốn sẽ có dạng:

image

Cách 1
getCountries(data: any) {
    let httpParams = new HttpParams();
    Object.keys(data).forEach(function (key) {
       httpParams = httpParams.append(key, data[key]);
    });

    return this.httpClient.get("/api/countries", httpParams )
}


Cách 2
getCountries(data: any) {
    return this.httpClient.get("/api/countries", {params: data} )
}

Lỗi xảy ra như sau

Nếu data truyền quan params có chứa các kí tự đặc biệt : Vd

(gt,createdTime,2022/11/11)|(gt,createdTime,2022/12/11). Có chứa kí tự  "|"

Nên khi request sẽ bị đổi thành

(gt,createdTime,2022/11/11)%7C(gt,createdTime,2022/12/11).  Kí tự   "|"  =>  "%7C"

Cách giải quyết

https://stackoverflow.com/questions/51942703/character-converting-into-space-in-httpparams-angular-6

Tạo File: urlencoder.ts


import {HttpParameterCodec} from '@angular/common/http'

export class CustomURLEncoder implements HttpParameterCodec {

    encodeKey(key: string): string {
        // bỏ encodeURIComponent(key) nếu không muốn url endcode key truyền lên
        return encodeURIComponent(key); 
    }
    encodeValue(value: string): string { 
        // bỏ encodeURIComponent(value) nếu không muốn url endcode giá trị params truyền lên
        return value; 
    }
    decodeKey(key: string): string { 
        return decodeURIComponent(key); 
     }
    decodeValue(value: string) {
        return decodeURIComponent(value); 
     }
}

Khi call API service

import {CustomURLEncoder} from './urlencoder';
import {HttpParams, HttpHeaders, HttpClient} from '@angular/common/http';

export class ApiService {
    constructor(private httpClient: HttpClient){}
    const fileDetails = new HttpParams({encoder: new CustomURLEncoder() })
        .set('filename','1 + 2 = 3')

    return this.httpClient.post(url, fileDetails);
}