I have some knowledge about Angularjs but I'm new to ASP.NET MVC. So I was following this https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api tutorial. But I came up with a problem as it uses Jquery. I want to access the hard coded data in below controller using Angular.
using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
namespace ProductsApp.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
I just want the method to access the data.
Can anyone help me with this. Thanks
Use $http
in your service or controller of AngularJS to access data from your Web API. For example:
$http.get("http://localhost:8080/api/products/getallproducts")
.then(function(response) {
console.log(response.data);
});
If writing WebApi application then you need to change the IHttpActionResult Name to Get. and try this URL:
localhost:8080/api/products/{id}
*{id} is optional.
if you want to use the route you should change WebApiConfig.cs
in App_Start folder.
Take a look at angularjs $http service which is used to establish communication with the http server in situation as yours.
To call GetAllProducts()
, using the $http
, use the route "api/products"
like this
$http.get("api/products")
.then(function(response) {
console.log(response);
});
And to call GetProduct()
use the route "api/products/1"
if your product is 1 like this
$http.get("api/products/1")
.then(function(response) {
console.log(response);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.