I am new to Angular2. I want to call an API using Angular2 in my MVC6 project. I have tried many things (including the guide at Angular2 calling ASP.NET Web API) without success.
I don’t know where I should start, or which files are needed.
I am new to Angular2. I want to call an API using Angular2 in my MVC6 project. I have tried many things (including the guide at Angular2 calling ASP.NET Web API) without success. I don’t know where I should start, or which files are needed. |
|||||||||
|
I'd look at some of the examples on Github to see how other people have done it. There are a number of things that have to be just right for it all to work, and the errors can be nebulous until you get it up and running. Add a Web API Controller Class to your project. Just to make sure everything is working at first, I'd suggest hard coding your HttpGet attribute to "api/values". ValuesController.cs. :
Startup.Cs. You need the angular2 routes to not interfere with ASP.NET's routes. This means you need to serve the index.html to the client if there is a 404 error. The app.Use lambda accomplishes this. Notice that it is before the calls to app.UseDefaultFiles() and app.UseStaticFiles()
Once you have this setup, you should test your API with Postman to make sure the routing is working as you want it to. If this doesn't work, it won't work in Angular. I have http://localhost:5001/ set as my App URL in my Visual Studio project Debug settings. If that is working correctly, move on to getting it to load with Angular 2. You'll need to use the base element just after the head tag in your html file. This tells the Angular router what the static part of the URL is: Index.html
Next you'll need to create a Service in Angular2 to Get the values from your API: dataService.ts
The .do operator in RxJS is very handy. It will allow you to debug that you are correctly getting the values from your API. See Andre Staltz's blog for more details. Finally, create a component to use the service: app.component.ts
|
||||
|
This is how I did it my application (angular2 as front-end with Web API core)-
[This is done to handle cross communication from localhost:3000 (angular2) to localhost:59024 (webapi)] First, add dependency in project.json - then enable CORS in startup.cs like this-
You can find more information about CORS here - https://docs.asp.net/en/latest/security/cors.html 3.In Angular2 front-end, you can write your service component like this-
See if this helps. |
||||
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?