1
votes

I have Web Api controller with route attribute applied on method defined like this:

[Route("api/[controller]")]
public DataController(
[HttpGet("getdata/{a:int}/{b:int}/{dateFrom:datetime}/{dateTo:datetime}")]
public IActionResult GetEvents(Int32 a, Int32 b, DateTime? dateFrom, DateTime? dateTo)
{
    if (ModelState.IsValid)
    {
            data = dataService.GetData(a,b,dateFrom, dateTo);
            return Ok(data);
        }

        return BadRequest();
    }
}

So the exposed web api URL would be: http://localhost:port/api/data/getdata/1/2/2016-10-12T00:00:00/2016-10-20T00:00:00

When I send GET request using Postman google chrome extension i can hit this controller action and URL params are parsed OK.

I'd like to get data from this web api using http get from angular2 client :

let params: URLSearchParams = new URLSearchParams();
params.set('a', 1);
params.set('b', 2);
params.set('dateFrom', '2016-10-12T00:00:00Z');
params.set('dateTo', '2016-10-15T00:00:00Z');

    return this._http.get(this._eventsUrl, {
        search: params
    }).map((response: Response) => <ModelObject[]>response.json())
        .catch(this.handleError);

this call trying to get data from this URL: http://localhost:PORT/api/data/getdata?a=1&b=1&dateFrom=2016-10-12T00:00:00Z&dateTo=2016-10-15T00:00:00Z

how can I set http.get from angular 2 to use URL like one defined in web api routing ?

1

1 Answers

1
votes

URLSearchParams adds params to the search part of the url, which is the part after the '?'.

You need to construct a variable which contains the entire url as in:

const url = `${this._eventsUrl}/${a}/${b}/${dateFrom}/${dateTo}`;

Note the use of backticks to construct a string which contains variables a, b, dateFrom, dateTo And call this.http.get(url).map