Mapping REST search endpoint onto $resource

ng-resource returns an object with the following default resource actions

  { 'get':    {method:'GET'},
    'save':   {method:'POST'},
    'query':  {method:'GET', isArray:true},
    'remove': {method:'DELETE'},
    'delete': {method:'DELETE'} };

I'm not sure exactly the best method for querying data from REST WebApi endpoints from AngularJS, but I've implemented Predicate Builder server-side in order to query my db using Linq. I have a (POST) endpoint named "Search()" @/api/Product/Search that will accept a searchCriteria JSON object which is deserialized, fed to the Linq predicate builder, and executed against the dbContext. My WebApi2 controller is structured like this, using the new route attribute feature:

  [RoutePrefix("Product")]
    public class ProductController : ApiController
    {
        [HttpGet]
        [Route("")]
        public IEnumerable<Product> Get()
        {
            try
            {
                return _productBL.Get();
            }
            catch
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        [HttpGet]
        [Route("{productId}")]
        public Product Get(string productId)
        {
            try
            {
                var product= _externalWorkStepBL.GetById(productId);
                if (product== null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return product;
            }
            catch (Exception)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        [HttpPost]
        public HttpResponseMessage Post([FromBody]Product product)
        {
            try
            {
                _productBL.Insert(product);
                var response = Request.CreateResponse(HttpStatusCode.Created, product);
                response.Headers.Location = new Uri(Request.RequestUri, string.Format("Product/{0}", product.workItemID));
                return response;
            }
            catch
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
        }

        [HttpPost]
        [Route("Search")]
        public IEnumerable<Product> Where([FromBody] SearchCriteria searchCriteria)
        {
            if (searchCriteria == null || (searchCriteria.FieldContainsList == null || searchCriteria.FieldEqualsList == null || searchCriteria.FieldDateBetweenList == null))
            {
                throw new HttpRequestException("Error in, or null, JSON");
            }
            return _productBL.Where(searchCriteria);
        }

        [HttpPut]
        [Route("")]
        public HttpResponseMessage Put([FromBody]Productproduct)
        {
            try
            {
                _productBL.Update(product);
                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Headers.Location = new Uri(Request.RequestUri, string.Format("Product/{0}", product.Id));
                return response;
            }
            catch ()
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        [HttpDelete]
        [Route("{productId}")]
        public void Delete(string productId)
        {
            HttpResponseMessage response;
            try
            {
                _productBL.Delete(productId);
                response = new HttpResponseMessage(HttpStatusCode.NoContent);
                response.Headers.Location = new Uri(Request.RequestUri, string.Format("Product/"));    
            }
            catch (Exception)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }
    }

On the client side I've wrapped $resource in a factory called $myResource, adding a PUT method. I then use $myResource for my other factories as follows:

var app = angular.module('App', ['ngResource'])  
    .factory('$myResource', ['$resource', function ($resource) {
    return function (url, paramDefaults, actions) {
        var MY_ACTIONS = {
            'update': { method: 'PUT' }      
        };
        actions = angular.extend({}, MY_ACTIONS, actions);
        return $resource(url, paramDefaults, actions);
    }
}])
    .service('ProductFactory', ['$myResource', function ($myResource) {
        return $myResource('/api/Product/:productId')
    }]);

This works great, but now I wish to add my Search endpoint. The Angular documentation for ng-Resource states that a url can be overridden in the action method, but it's not clear to me how to do this. I'm able to add the "search" action to $myResource, but how do I modify the url in the ProductFactory?

 .factory('$myResource', ['$resource', function ($resource) {
        return function (url, paramDefaults, actions) {
            var MY_ACTIONS = {
                'update': { method: 'PUT' },        
                'search': { method: 'POST','params': { searchCriteria: '@searchCriteria' }, isArray: true }   
            };
            actions = angular.extend({}, MY_ACTIONS, actions);
            return $resource(url, paramDefaults, actions);
        }
    }])  

As it currently is, calling ProductFactory.search(searchCriteria) sends a POST request with the correct JSON, but to the wrong url, "/api/Product". I need it to post to "/api/Product/Search". How can I modify $myResource to use "api/xxx/Search" where xxx is the controllername?


Nevermind! Didn't expect this to work, but it does.

.factory('$myResource', ['$resource', function ($resource) {
            return function (url, paramDefaults, actions) {
                var searchUrl = url + "/Search/:searchCriteria"
                var MY_ACTIONS = {
                    'update': { method: 'PUT' },        //add update (PUT) method for WebAPI endpoint 
                    'search': { method: 'POST', url : searchUrl,'params': { searchCriteria: '@searchCriteria' }, isArray: true }     //add Search (POST)
                };
                actions = angular.extend({}, MY_ACTIONS, actions);
                return $resource(url, paramDefaults, actions);
            }
        }])    
链接地址: http://www.djcxy.com/p/89554.html

上一篇: ngResource的正确配置

下一篇: 将REST搜索端点映射到$资源