AngularJS’s $resouce service makes integrating WebAPI with client applications easier.
This post introduces an example of ASP.NET WebAPI as follows.
Implement ASP.NET WebAPI
ProductsController.cs
public class ProductsController : ApiController
{
// GET api/products
public IEnumerable<Product> GetProducts()
{
return db.Products.AsEnumerable();
}
}
Web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<system.webServer>
$resouce service
JavaScript file (using AngularJS)
var productRepository = $resource('http://localhost:44312/api/products/:id', { id: '@Id' });
// Call "GET /api/products"
$scope.products = productRepository.query();
View html
<ul>
<li ng-repeat="product in products">{{product.name}}</li>
</ul>
$save() and $remove() methods
productRepository.query() returns an array of deserialized objects.
AngularJS adds CRUD methods ($save, $remove, etc…) to these objests.
For example:
product.name = "New Name";
product.$save();
$save() sends “POST /api/products/1” request with setting “{“id”:1,”name”:”New Name”}” to the request body.
Similarly, product.$remove() sends “DELETE /api/products/1” request.