AngularJS - 将REST搜索端点映射到$ resource

时间:2014-08-29 23:40:13

标签: angularjs asp.net-web-api2 ngresource

ng-resource返回具有以下默认资源操作的对象

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

我不确定从AngularJS查询来自REST WebApi端点的数据的最佳方法,但我已经实现了Predicate Builder服务器端,以便使用Linq查询我的数据库。我有一个名为“Search()”@(api / Product / Search的(POST)端点,它将接受一个searchCriteria JSON对象,该对象被反序列化,提供给Linq谓词构建器,并针对dbContext执行。我的WebApi2控制器的结构如下,使用新的路由属性功能:

  [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);
            }
        }
    }

在客户端,我将$ resource包装在一个名为$ myResource的工厂中,添加了一个PUT方法。然后我将$ myResource用于我的其他工厂,如下所示:

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')
    }]);

这很好用,但现在我希望添加我的搜索端点。 Angular documentation for ng-Resource表示可以在操作方法中覆盖网址,但我不清楚如何执行此操作。我可以将“搜索”操作添加到$ myResource,但是如何修改ProductFactory中的url?

 .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);
        }
    }])  

目前,调用ProductFactory.search(searchCriteria)会发送一个带有正确JSON的POST请求,但是错误的网址是“/ api / Product”。我需要它发布到“/ api / Product / Search”。如何修改$ myResource以使用“api / xxx / Search”,其中xxx是控制器名称?

1 个答案:

答案 0 :(得分:4)

没关系!没想到这会起作用,但确实如此。

.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);
            }
        }])