Tom el Safadi
Tom el Safadi

Reputation: 6766

Angular URLSearchParams not working for multiple params

I have an Asp.Net web api controller like this:

[HttpPost]
public IHttpActionResult RepHistorie([FromUri]string vnr, [FromUri]string lagerort)
{
    ...
}

So you can see that there are 2 values. I am using URLSearchParams for sending the parameters. Unfortunately this doesn't work for more than one param. I don't know why and this is really strange to me.

let params: URLSearchParams = new URLSearchParams();
params.set('vnr', this.vnr);
params.set('lagerort', this.lagerort);

var postUrl = 'http://123.456.7.89:12345/api/lager';

let requestOptions = new RequestOptions();
requestOptions.search = params;

this.http.post(postUrl, requestOptions)
  .subscribe(data => {
    // success

  }, error => {
    // error
});

In my other controller there is only one parameter and it works perfectly. Does someone know why?

I also tried:

params.append('vnr', this.vnr);
params.append('lagerort', this.lagerort);

Edit

It works like this (Isn't a clean way though):

var postUrl = 'http://123.456.7.89:12345/api/lager?vnr=' + this.vnr + '&lagerort=' + this.lagerort;
var postObject = {};

Upvotes: 4

Views: 3359

Answers (2)

ErvTheDev
ErvTheDev

Reputation: 4507

I had the same issue before noticing that i had not imported it, you have to import URLSearchParams before using it.

import {URLSearchParams} from '@angular/http';

Enjoy coding!

Upvotes: 11

Pfeiff86
Pfeiff86

Reputation: 142

It works for me with the following

    let params: URLSearchParams = new URLSearchParams();
    params.set('vnr', this.vnr);
    params.set('lagerort', this.lagerort);
    let requestOptions = new RequestOptions();
    requestOptions.params = params; // instead of requestOptions.search = params

Upvotes: 0

Related Questions