通过id以及字符串angularjs-webapi获取



我对angularjs使用webapi完全陌生,我可能做得不对,但基本上我想通过文本搜索产品(因为我在数据库中执行查询),并通过id获取产品,以更新现有产品。

按文本搜索我做如下。

//productResource.js
        (function () {
        "use strict";
        angular.module("common.services").factory("productResource", ["$resource", "appSettings", productResource])
        function productResource($resource, appSettings) {
            return $resource(appSettings.serverPath + "/api/products/:search");
        }
    }());

在我的webApi控制器

public IEnumerable<Product> Get(string search)
        {
            var repository = new ProductRepository();
            return repository.Restrieve(search); 
        }
        public Product Get(int id)
        {
            Product product;
            var repository = new ProductRepository();
            if (id > 0)
            {
                product = repository.GetProductById(id);
            }
            else
            {
                product = repository.CreateProduct();
            }
            return product;
        }

然后在我的WebApiConfig:中

 config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{search}",
            defaults: new { search = RouteParameter.Optional }
        );

按照现在的设置方式,我可以通过文本进行搜索。

如何配置productResource.jsWebApiConfig,以便按id进行搜索?

我会在这里选择稍微不同的路线。在RESTful API中,您有资源(在您的情况下是产品)。资源由id唯一标识。所以我会有以下路线:

GET /products/:id

如果我想通过文本搜索多个产品:

GET /products?search=xxxx

这对于默认路由来说是很好的:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

现在在客户端:

function productResource($resource, appSettings) {
    return $resource(appSettings.serverPath + 'api/products/:id');
}

和查询:

productResource.query({ id: '123'});
productResource.query({ search: 'some search text'});

这是一个nice overview,其中包含$resource的示例。

还要确保在下次尝试将搜索文本(或来自客户端的任何任意数据)放在路由的路径部分而不是它们所属的位置->查询字符串之前,您已经阅读了following blog post

最新更新