Im having a JSON object and passing it using HttpParams but it coverts + to space and sent to backend. I have tried all possible ways but no one solved it for an JSONObject string.
this.updateUser({"name":"ABC","mobile": "+911234567890","text":"1 + 2 = 3"});
public updateUser(myObj) {
const body = new HttpParams().set('user_object', JSON.stringify(myObj));
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
When I inspect in Network that object containing + character automatically converts into space.
This is a problem with HttpParams in angular. The +
in a parameter value is converted to a . I had a similar problem wherein I had a POST request which accepts file in the form of Base64 encoded string. This Base64 conversion of the file can contain a
+
sign which was getting converted to a . I implemented a CustomURLEncoder in my project to handle the same. Following is the snippet for your reference:
import {HttpParameterCodec} from '@angular/common/http'
export class CustomURLEncoder implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(key: string): string {
return encodeURIComponent(key);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(key: string) {
return decodeURIComponent(key);
}
}
And you can use the encoder with the HttpParams as follows:
import {CustomURLEncoder} from './urlencoder.component';
import {HttpParams, HttpHeaders, HttpClient} from '@angular/common/http';
export class ApiService {
constructor(private httpClient: HttpClient){}
base64 = "Encoded+Base64+File+Data" //String with '+'
const fileDetails = new HttpParams({encoder: new CustomURLEncoder() })
.set('filename','CustomEncodedFile.xlsx')
.set('filedata',base64);
return this.httpClient.post(url, fileDetails, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-
form-urlencoded;charset=utf-8')
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With