Pass '+'(plus) character by URLSearchParams in Angular2

  • Posted on: 1 August 2017
  • By: jmu

Recently, I am working on Angular 2. When I tried to send the description by POST request, I found that the '+'(plus) sign cannot be passed to my backend. Then, I read the official document here, and found the reason.

Description

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

But they also provide a solution if you have to use these characters. I will give an example in this blog.

//In my cart.component.ts file
import { Component, OnInit} from '@angular/core';
import { URLSearchParams, Headers, QueryEncoder } from '@angular/http';
@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css'],
  providers: [DBService]
})

class GhQueryEncoder extends QueryEncoder { // encode + plus sign
    encodeKey(k: string): string {
        k = super.encodeKey(k);
        return k.replace(/\+/gi, '%2B');
    }
    encodeValue(v: string): string {
        v = super.encodeKey(v);
        return v.replace(/\+/gi, '%2B');
    }
}

export class CartComponent implements OnInit {
  constructor() {
  }
  private update() {
    let urlSearchParams = new URLSearchParams('', new GhQueryEncoder());
    urlSearchParams.append('ticketDetailId', this.ticketDetailID.toString());
    urlSearchParams.append('itemQty', this.itemQty.toString());
    urlSearchParams.append('itemPrice', this.itemPrice.toString());
    const postValue_body = urlSearchParams.toString();
    this._dbService.post('itemUpate.php', postValue_body);
  }

}

After adding the GhQueryEncoder class, my submission form works perfectly.

Comments

Comment: 
Thank you!

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.