Introduction

Most applications today have similarities when it comes to separating the front-end and back-end. It means that the back-end can be hosted anywhere in the cloud or on a dedicated server. There can be many REST services. It can be developed in any programming language, using any development tools of your choice. The same can happen to the front-end, you can go from a Single Page Application (SPA) loading everything through Ajax or use any framework to render your data from the server synchronously.
In this article, you’ll learn how to create Angular application by consuming ASP.NET WEB API Core and how to build and run an Angular application using Docker container services.
Prerequisites
  • Node.js, which is a prerequisite for Angular
  • Visual Studio Code, or any other editor you like
  • Visual Studio for developing ASP.NET WEB API Core
Background
  • Basic knowledge of Javascript
  • Familiarity with HTML and CSS
  • ASP.NET Core, MVC, and C#
What's Next?
Let's start building ASP.NET WEB API step by step and then build Angular application for front-end and consume web api using ajax call. Once these two are completed we will create a Docker image of Angular application and run the image on Docker container service. Let's start one by one in detail.
Create a Product Model:
  1. namespace ASPNETWebAPI
  2. {
  3. public class Product
  4. {
  5. public int Id { get; set; }
  6. public string Name { get; set; }
  7. public string Category { get; set; }
  8. public decimal Price { get; set; }
  9. }
  10. }
Create a WEB API Controller and Action Methods:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Cors;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Mvc;
  8. namespace ASPNETWebAPI.Controllers
  9. {
  10. [Route("api/[controller]")]
  11. [ApiController]
  12. public class ProductController : ControllerBase
  13. {
  14. Product[] products = new Product[]
  15. {
  16. new Product
  17. {
  18. Id = 1, Name = "Soup", Category = "Groceries", Price = 1
  19. },
  20. new Product
  21. {
  22. Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M
  23. },
  24. new Product
  25. {
  26. Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M
  27. }
  28. };
  29. [HttpGet]
  30. [EnableCors("AllowOrigin")]
  31. public IEnumerable<Product> GetAllProducts()
  32. {
  33. return products;
  34. }
  35. [HttpGet("{id}")]
  36. [EnableCors("AllowOrigin")]
  37. public ActionResult<Product> GetProduct(int id)
  38. {
  39. var product = products.FirstOrDefault((p) => p.Id == id);
  40. if (product == null)
  41. {
  42. return NotFound();
  43. }
  44. return product;
  45. }
  46. }
  47. }
Install Microsoft.AspNet.WebApi.Cors to enable Cross-Origin Resource Sharing (CORS) in ASP.NET Web API Core.
  1. PM> Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.7
Modify Startup.cs to enable Cross-Origin Resource Sharing (CORS) in ASP.NET Web API Core.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.HttpsPolicy;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.Hosting;
  12. using Microsoft.Extensions.Logging;
  13. namespace ASPNETWebAPI
  14. {
  15. public class Startup
  16. {
  17. public Startup(IConfiguration configuration)
  18. {
  19. Configuration = configuration;
  20. }
  21. public IConfiguration Configuration { get; }
  22. // This method gets called by the runtime. Use this method to add services to the container.
  23. public void ConfigureServices(IServiceCollection services)
  24. {
  25. services.AddControllers();
  26. services.AddCors(c =>
  27. {
  28. c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
  29. });
  30. }
  31. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  32. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  33. {
  34. if (env.IsDevelopment())
  35. {
  36. app.UseDeveloperExceptionPage();
  37. }
  38. app.UseHttpsRedirection();
  39. app.UseRouting();
  40. app.UseAuthorization();
  41. app.UseCors(option => option.AllowAnyOrigin());
  42. app.UseEndpoints(endpoints =>
  43. {
  44. endpoints.MapControllers();
  45. });
  46. }
  47. }
  48. }
Now let's move on to our Angular aplication. Use Visual Studio code editor to develop the Angular application.
Install Angular CLI using the below command.
  1. npm install -g @angular/cli
Create a new Angular application using the below command.
  1. ng new dotnetcore-angular
Once the new application has been created, run the application using the below command.
  1. ng serve
Open the application in the browser using http://localhost:4200/
Now let's modify the application to consume REST Service.
Create product.ts in app folder.
  1. export class Product {
  2. id: number;
  3. name: string;
  4. category: string;
  5. price: number;
  6. }
Create ProductService.ts to consume data from REST Service.
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { Product } from './Product';
  4. import { Observable, throwError } from 'rxjs';
  5. import { retry, catchError } from 'rxjs/operators';
  6. @Injectable({
  7. providedIn: 'root'
  8. })
  9. export class ProductService {
  10. // Define API
  11. apiURL = 'https://localhost:44389/api/Product';
  12. constructor(
  13. private http: HttpClient
  14. ) { }
  15. // HttpClient API get() method => Fetch Product list
  16. getProduct(): Observable<Product[]> {
  17. return this.http.get<Product[]>(this.apiURL)
  18. .pipe(
  19. retry(1),
  20. catchError(this.handleError)
  21. )
  22. }
  23. // Error handling
  24. handleError(error) {
  25. let errorMessage = '';
  26. if(error.error instanceof ErrorEvent) {
  27. // Get client-side error
  28. errorMessage = error.error.message;
  29. } else {
  30. // Get server-side error
  31. errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
  32. }
  33. window.alert(errorMessage);
  34. return throwError(errorMessage);
  35. }
  36. }
Let's modify the app.component.ts file read the data from ProductService.ts.
  1. import { Component, OnInit } from '@angular/core';
  2. import {ProductService} from '../app/ProductService';
  3. @Component({
  4. selector: 'app-root',
  5. templateUrl: './app.component.html',
  6. styleUrls: ['./app.component.less']
  7. })
  8. export class AppComponent implements OnInit {
  9. Product : any = [];
  10. constructor(
  11. private productService : ProductService
  12. ) { }
  13. ngOnInit() {
  14. this.getAllProducts()
  15. }
  16. // Get Product list
  17. getAllProducts() {
  18. return this.productService.getProduct().subscribe((data: {}) => {
  19. this.Product = data;
  20. })
  21. }
  22. }
Finally, let's modify the app.component.html to render the data in the UI.
  1. <div>
  2. <h3 class="mb-3 text-center">Product List</h3>
  3. <div class="col-md-12">
  4. <table class="table table-bordered">
  5. <thead>
  6. <tr>
  7. <th scope="col"> Id</th>
  8. <th scope="col">Name</th>
  9. <th scope="col">Category</th>
  10. <th scope="col">Price</th>
  11. </tr>
  12. </thead>
  13. <tbody>
  14. <tr *ngFor="let product of Product">
  15. <td>{{product.id}}</td>
  16. <td>{{product.name}}</td>
  17. <td>{{product.category}}</td>
  18. <td>{{product.price}}</td>
  19. </tr>
  20. </tbody>
  21. </table>
  22. </div>
  23. </div>
We are done with the development,lets create docker image of this application and run on docker container service. Below are commands which will build Docker image and run on Docker container service. Beforehand, you need to install Docker Deskop to your machine. This will enable Docker commands.
Command for building the docker image.
  1. docker build -t dotnetcore-angular .
Command to see a list of docker images.
  1. docker image ls
Command to run Docker. This command will create a container for the Docker image on the specified port.
  1. docker run --name dotnetcore-angular-container -d -p 8080:80 dotnetcore-angular
Command to see a list of available Docker containers.
  1. docker container ls
Push Docker Image to Docker Hub
Before pushing the docker image into Docker Hub you need to have a Docker account. Once the Docker account is created using the below command to push the Docker image to Docker Hub.
  1. docker tag docker-angular-test:v1 rchandra1/ravindra:docker-angular
You can see the Docker image after pushed to Docker Hub.
Learn How To Build Angular Application With ASP.NET Web API Core And Create Docker Image And Run Using Docker Container Service