Hello guys Here in this article i am going to show you , how to call web api from our angular 2 / 4 application from a service file
first of all we should know basics about angular and its services
And other most important thing is that , we know how to create and consume web api in angular 2
So lets create service file inside our project Note : i am not going to write whole file code , because service in Angular2 automatically create predefine structure for us
Step : 1 Create method inside service file (StudService.ts file) constructor(private _httpp : HTTP) // where http is service , calls actual methods of it
{ }
let mainApiUrl = "http://localhost:55555/api/Students"; // Student is API Controller Name
GetStudents()
{
return this._httpp.get(this.mainApiUrl).map((response) => response.json() );
}
So as you can see , _httpp.get() calls for Get() request from API Handler
Step : 2 Call Delete Method As we saw above that Get() is called using get() method , same way Delete operation can be called using delete() of http method
So lets see how to implement that :
let DeleteUrl = "http://localhost:55555/api/Students";
DeleteStudentById()
{
return this._httpp.delete(this.mainApiUrl+ "/" + id).map((response) => response.json() );
}
Explaination : delete() -> this will call the delete of an http method delete() , based on given id
id -> ID is a student id for which we want to delete an specific student
Step : 3 Post an Student As we saw in MVC we can add data using post request , same way we can also use POST in ASP.NET MVC Web API an POST Request
Lets implement post request via service in angular 2
let postAPIUrl = "http://localhost:55555/api/Students";
PostStudentData()
{
this._httpp.post(this.postAPIUrl , body).map((response) => response.json() );
}
Code explaination : post() -> post method automatically call web api's post method request where data collection to be posted
body -> Body is a collection of data , that is being collected in .ts file of angular 2 component file
E.G : we have student class and data like : ID,
Name,
Gender,
Email,
Phone,
Location
etc are collected data that are we previously got via filling the form , its like entity or a array of an different types .
So that's the way to implement
WEB Api call from Angular 2 service class
If you want more about this please follow :
asp-dotnet-mvc-tutorials.blogspot.com Feel free to ask me if you found something wrong or suggest me if i missed something
Thanks
Manav Pandya