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.
- 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:
- namespace ASPNETWebAPI
- {
- public class Product
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Category { get; set; }
- public decimal Price { get; set; }
- }
- }
Create a WEB API Controller and Action Methods:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Cors;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
-
- namespace ASPNETWebAPI.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
-
- public class ProductController : ControllerBase
- {
- Product[] products = new Product[]
- {
- new Product
- {
- Id = 1, Name = "Soup", Category = "Groceries", Price = 1
- },
- new Product
- {
- Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M
- },
- new Product
- {
- Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M
- }
- };
-
- [HttpGet]
- [EnableCors("AllowOrigin")]
- public IEnumerable<Product> GetAllProducts()
- {
- return products;
- }
-
- [HttpGet("{id}")]
- [EnableCors("AllowOrigin")]
- public ActionResult<Product> GetProduct(int id)
- {
- var product = products.FirstOrDefault((p) => p.Id == id);
- if (product == null)
- {
- return NotFound();
- }
- return product;
- }
- }
- }
Install Microsoft.AspNet.WebApi.Cors to enable Cross-Origin Resource Sharing (CORS) in ASP.NET Web API Core.
- 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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
-
- namespace ASPNETWebAPI
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers();
- services.AddCors(c =>
- {
- c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
- });
-
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseHttpsRedirection();
-
- app.UseRouting();
-
- app.UseAuthorization();
- app.UseCors(option => option.AllowAnyOrigin());
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
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.
- npm install -g @angular/cli
Create a new Angular application using the below command.
- ng new dotnetcore-angular
Once the new application has been created, run the application using the below command.
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.
- export class Product {
- id: number;
- name: string;
- category: string;
- price: number;
- }
Create ProductService.ts to consume data from REST Service.
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { Product } from './Product';
- import { Observable, throwError } from 'rxjs';
- import { retry, catchError } from 'rxjs/operators';
-
- @Injectable({
- providedIn: 'root'
- })
- export class ProductService {
-
- apiURL = 'https://localhost:44389/api/Product';
- constructor(
- private http: HttpClient
- ) { }
-
-
-
- getProduct(): Observable<Product[]> {
- return this.http.get<Product[]>(this.apiURL)
- .pipe(
- retry(1),
- catchError(this.handleError)
- )
- }
-
- handleError(error) {
- let errorMessage = '';
- if(error.error instanceof ErrorEvent) {
-
- errorMessage = error.error.message;
- } else {
-
- errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
- }
- window.alert(errorMessage);
- return throwError(errorMessage);
- }
-
- }
Let's modify the app.component.ts file read the data from ProductService.ts.
- import { Component, OnInit } from '@angular/core';
- import {ProductService} from '../app/ProductService';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.less']
- })
- export class AppComponent implements OnInit {
- Product : any = [];
- constructor(
- private productService : ProductService
- ) { }
- ngOnInit() {
- this.getAllProducts()
- }
-
-
- getAllProducts() {
- return this.productService.getProduct().subscribe((data: {}) => {
- this.Product = data;
- })
- }
- }
Finally, let's modify the app.component.html to render the data in the UI.
- <div>
- <h3 class="mb-3 text-center">Product List</h3>
-
- <div class="col-md-12">
- <table class="table table-bordered">
- <thead>
- <tr>
- <th scope="col"> Id</th>
- <th scope="col">Name</th>
- <th scope="col">Category</th>
- <th scope="col">Price</th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let product of Product">
- <td>{{product.id}}</td>
- <td>{{product.name}}</td>
- <td>{{product.category}}</td>
- <td>{{product.price}}</td>
-
- </tr>
- </tbody>
- </table>
- </div>
- </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.
- docker build -t dotnetcore-angular .
Command to see a list of docker images.
Command to run Docker. This command will create a container for the Docker image on the specified port.
- docker run --name dotnetcore-angular-container -d -p 8080:80 dotnetcore-angular
Command to see a list of available Docker containers.
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.
- docker tag docker-angular-test:v1 rchandra1/ravindra:docker-angular
You can see the Docker image after pushed to Docker Hub.