Search code examples
angularjsparametersangular-resource

Passing a Complex Parameter into a Query in AngularJs


I have seen 100 examples of passing an ID into $resource.get() in order to query information out of a back-end in Angular. What I have not been able to find is how to pass a complex object.

If I have a table of objects to return, and I wish to run a search against them using multiple items of filter, I need to pass those items as parameters or as one complex parameter. For example, say I have a table of people's names and their cities, states, etc. I want to be able to say something like this:

var myResource = $resource(url);
myResource.get({name : "Mike", state : "Texas"});

The return may be a single row or multiple rows. But the point is how do I get the parameters off to the API call?

The way I have other methods set up that are simpler is by creating a repository in which I return like so:

return resource('/api/broker/productionInfo/');

Then in my API I do this (after the [RoutePrefix("api/broker")] setup:

[HttpGet]
[Route("productionInfo")]
public IHttpActionResult GetProductions()
{}

That's all awesome but I want to be able to add the search criteria in the repository call and then in the API method (i.e. extract from a querystring or however it is to be passed).


Solution

  • The only thing I'm seeing that you're missing is a [FromUri] decorate attribute, in your GetProduction API method. Since Get supports only params binding through a query string (no body binding).

    Your params:

    options: {
        StartDate: _startDate
        EndDate: _endDate
        TextSearch: "some search query....",
        Page: 1,
        PageSize: 25,
        et...
    }
    

    Then, calling your repository from your controller:

    repository.get(options).$promise.then(function (data) {
        // data =  response payload from backend
    });
    

    reposiroty

    ....
        return resource('/api/broker/productionInfo/');
    ....
    

    API

    [HttpGet]
    [Route("productionInfo")]
    public IHttpActionResult GetProductions([FromUri] SearchCriteriaModel criteria) {
        ....
    }
    

    Hope that helps.