Home > Mobile >  Query params encoding while making API call
Query params encoding while making API call

Time:09-29

When I have a special charachter in the query params, the URL is getting encoded, how can I prevent url encoding while making an http get call.

I tried

export class AppComponent {
  codec = new HttpUrlEncodingCodec();
  name = 'Angular';
  baseUrl = 'https://jsonplaceholder.typicode.com/';

  constructor(private http: HttpClient) {
    const params = new HttpParams().set(
      this.codec.decodeValue('userId[]'),
      '1'
    );
    this.http
      .get(this.baseUrl   'posts', { params: params })
      .subscribe((data) => {
        this.name = this.name.concat(data[0].title);
      });
  }
}

I tried to do with HttpUrlEncodingCodec but it is not working for me

but still URL looks like:

https://jsonplaceholder.typicode.com/posts?userId[]=1

I want it to look like

https://jsonplaceholder.typicode.com/posts?userId[]=1

like userId[], I have multiple query params. How can I prevent encoding of query params in Angular

CodePudding user response:

After chatting in the dedicated room you explained to me your need and here is the final solution, which is the simplest you can find :

    const params = { 'userId[]': [1, 2, 3] };

    const paramStr = Object.entries(params)
      .map(([key, value]) => `${key}=${value.join(',')}`)
      .join('&');

    this.http.get('http://www.test.com?'   paramStr).subscribe();

Working stackblitz (Open the network dev tools)

Other solutions involve rewriting an encoder and providing it to the http module. I'm not a fan of that, when you can just use a one liner to do the same thing.

CodePudding user response:

export class AppComponent {
  codec = new HttpUrlEncodingCodec();
  name = 'Angular';
  baseUrl = 'https://jsonplaceholder.typicode.com/';

  constructor(private http: HttpClient) {
    const params = { 'userId[]': 1 };
    this.http
      .get(this.baseUrl   'posts', { params })
      .subscribe((data) => {
        this.name = this.name.concat(data[0].title);
      });
  }
}
  • Related