To complete this implementation I have used Visual Studio 2017 to create an ASP.Net Web API and Visual Studio Code to create an Angular App.
How to create ASP.Net Web API?
Read:- Angular Interview Questions
public IEnumerable<string> Get() { List<string> productName = new List<string>(); productName.Add(“Laptop”); productName.Add(“TV”); productName.Add(“Washing Machine”); productName.Add(“Mobile”); productName.Add(“Tablet”); return productName; } |
6. Now, hit F5 to run your Web API. To test your API add /api/values to display data on browser.
7. To consume this Web API from Angular, we have to enable CORS in our API. To enable CORS, the very first step is to install AspNet.WebApi.Cors.
To do this, run below command in package manager console in Visual Studio 2017.
Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.7
8. Once the installation is done, we have to add EnableCors attribute to either a particular Action or to the Controller class.
[EnableCors(origins: “http://localhost:4200”, headers: “*”, methods: “*”)] |
9. We have to enable cors in WebApiConfig file as well, as shown in below screen shot.
Once your Web API is ready, then run your API to see the result and keep the API running.
How to create Angular App?
1. To create an Angular App, open command prompt and type -> ng new myProject
This command will create a basic Angular App for you.
2. Now, create a new component by using below command. This component wil be used to consume and display data fetched from API.
ng g c /demo/apitest
This will create a new component in app->demo->apitest folder.
3. Open your root module. Generally, it is app.module.ts, import HttpClientModule from ‘@angular/common/http’
4. Open apitest.component.ts file and inject HttpClient
5. Now, write below code in ApitestComponent class.
6. Open apitest.component.html and write below code.
Hope, you like this blog. Please share the URL and to give feedback please write your comment below.
You may like other blogs –
MVC Tutorial
Web API Tutorial
CRUD Example with Angular
Building Blocks of Angular
Learn TypeScript
Interview Questions and Answers Series –
MVC Interview Questions and Answers
Web API interview questions and answers
Keep following – SharePointCafe.Net
Prev – Call API service from Angular App
Next – Pipes in Angular