Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'+' character converting into space in HttpParams angular 6

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.

like image 346
Vinay Sharma Avatar asked Aug 21 '18 06:08

Vinay Sharma


1 Answers

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')
    });
}
like image 70
Jahnavi Paliwal Avatar answered Sep 30 '22 00:09

Jahnavi Paliwal