Learn How to Build an Angular Application With ASP.NET Web API Core, Create a Docker Image, and Run Using Docker Container Services

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 { getset; }    
  6.         public string Name { getset; }    
  7.         public string Category { getset; }    
  8.         public decimal Price { getset; }    
  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.     
  9. namespace ASPNETWebAPI.Controllers    
  10. {    
  11.     [Route("api/[controller]")]    
  12.     [ApiController]    
  13.         
  14.     public class ProductController : ControllerBase    
  15.     {    
  16.         Product[] products = new Product[]    
  17.         {    
  18.             new Product    
  19.             {    
  20.                 Id = 1, Name = "Soup", Category = "Groceries", Price = 1    
  21.             },    
  22.             new Product    
  23.             {    
  24.                 Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M    
  25.             },    
  26.             new Product    
  27.             {    
  28.                 Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M    
  29.             }    
  30.         };    
  31.     
  32.         [HttpGet]    
  33.         [EnableCors("AllowOrigin")]    
  34.         public IEnumerable<Product> GetAllProducts()    
  35.         {    
  36.             return products;    
  37.         }    
  38.     
  39.         [HttpGet("{id}")]    
  40.         [EnableCors("AllowOrigin")]    
  41.         public ActionResult<Product> GetProduct(int id)    
  42.         {    
  43.             var product = products.FirstOrDefault((p) => p.Id == id);    
  44.             if (product == null)    
  45.             {    
  46.                 return NotFound();    
  47.             }    
  48.             return product;    
  49.         }    
  50.     }    
  51. }    
 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.     
  14. namespace ASPNETWebAPI    
  15. {    
  16.     public class Startup    
  17.     {    
  18.         public Startup(IConfiguration configuration)    
  19.         {    
  20.             Configuration = configuration;    
  21.         }    
  22.     
  23.         public IConfiguration Configuration { get; }    
  24.     
  25.         // This method gets called by the runtime. Use this method to add services to the container.    
  26.         public void ConfigureServices(IServiceCollection services)    
  27.         {    
  28.             services.AddControllers();    
  29.             services.AddCors(c =>    
  30.             {    
  31.                 c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());    
  32.             });            
  33.                     
  34.         }    
  35.     
  36.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.    
  37.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    
  38.         {    
  39.             if (env.IsDevelopment())    
  40.             {    
  41.                 app.UseDeveloperExceptionPage();    
  42.             }    
  43.     
  44.             app.UseHttpsRedirection();    
  45.     
  46.             app.UseRouting();    
  47.     
  48.             app.UseAuthorization();    
  49.             app.UseCors(option => option.AllowAnyOrigin());    
  50.     
  51.             app.UseEndpoints(endpoints =>    
  52.             {    
  53.                 endpoints.MapControllers();    
  54.             });    
  55.         }    
  56.     }    
  57. }    
 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.   
  7. @Injectable({  
  8.   providedIn: 'root'  
  9. })  
  10. export class ProductService {  
  11.     // Define API  
  12.   apiURL = 'https://localhost:44389/api/Product';  
  13.   constructor(  
  14.     private http: HttpClient  
  15.   ) { }  
  16.   
  17.     
  18.   // HttpClient API get() method => Fetch Product list  
  19.   getProduct(): Observable<Product[]> {  
  20.     return this.http.get<Product[]>(this.apiURL)  
  21.     .pipe(  
  22.       retry(1),   
  23.       catchError(this.handleError)  
  24.     )  
  25.   }  
  26.  // Error handling   
  27.  handleError(error) {  
  28.     let errorMessage = '';  
  29.     if(error.error instanceof ErrorEvent) {  
  30.       // Get client-side error  
  31.       errorMessage = error.error.message;  
  32.     } else {  
  33.       // Get server-side error  
  34.       errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;  
  35.     }  
  36.     window.alert(errorMessage);  
  37.     return throwError(errorMessage);  
  38.  }  
  39.     
  40. }  
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.   
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.less']  
  8. })  
  9. export class AppComponent implements OnInit {  
  10.   Product : any = [];  
  11.   constructor(  
  12.     private productService : ProductService  
  13.     ) { }  
  14.     ngOnInit() {  
  15.       this.getAllProducts()  
  16.     }  
  17.   
  18.     // Get Product list  
  19.   getAllProducts() {  
  20.     return this.productService.getProduct().subscribe((data: {}) => {  
  21.       this.Product = data;  
  22.     })  
  23. }  
  24. }  
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.   
  4.     <div class="col-md-12">  
  5.       <table class="table table-bordered">  
  6.         <thead>  
  7.           <tr>  
  8.             <th scope="col"> Id</th>  
  9.             <th scope="col">Name</th>  
  10.             <th scope="col">Category</th>  
  11.             <th scope="col">Price</th>              
  12.           </tr>  
  13.         </thead>  
  14.         <tbody>  
  15.           <tr *ngFor="let product of Product">  
  16.             <td>{{product.id}}</td>  
  17.             <td>{{product.name}}</td>  
  18.             <td>{{product.category}}</td>  
  19.             <td>{{product.price}}</td>  
  20.               
  21.           </tr>  
  22.         </tbody>  
  23.       </table>  
  24.     </div>  
  25.   </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


Similar Articles