Click here to Skip to main content
14,299,664 members

Code Example for SPA and Micro-Service on Azure

Rate this:
5.00 (1 vote)
Please Sign up or sign in to vote.
5.00 (1 vote)
12 Sep 2019CPOL
This is a demonstration of a basic example of single page Angular application and micro-service architecture on Azure.

Introduction

This is a demonstration of a basic example of single page Angular application and micro-service architecture. Angular application uses adal-angular4 to authenticate Azure Active Directory users.

Background

SPA and micro-service is the trend for modern web application. Moreover, there is a high need of auto-scalability and well-supported Cloud environment. Last but not the least, that is a single sign-on ability and easy to integrate any Identity Provider.

Image 1

Using the Code

https://github.com/quinvit/microcore/tree/master/Sample/Angular

  1. time-tracker-ui folder contains sample code of Angular application
  2. TimeTrackerAPI folder contains sample code of API Gateway
  3. Services folder contains sample code of two simple microservices

The API Gateway and micro-services are deployed to Azure Web App (linux docker container mode) in order that we can easily scale up or scale out any service. On the other hand, hosting microservice in Azure Web App is much cheaper than on VM or AKS.

Image 2

The communication between micro-services is asynchronous HTTP and is handled by https://github.com/quinvit/microcore library. The library covers network call, serialization/deserialization, contract mapping. We only use micro-service by using DI to inject service interface to constructor as in-process service injection.

In Angular frontend, we simply use adal-angular4 library to authenticate against Azure Active Directory users and auto-attach jwt bearer token when we call any API using HttpClient.

 @Component({
  selector: 'app-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.css']
})
export class ReportsComponent implements OnInit {

  displayedColumns: string[] = ['name', 'totalMinutes', 'dayInMonth', "email"];
  dataSource = ELEMENT_DATA;

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.http.get<DailyTimeSheetByUser[]>
          (`${environment.config.apiGateway}/api/Reports/MonthlyReportByUser`)
      .subscribe(x => {
        this.dataSource = x;
      });
  }
}

For more details about this library, please take a look at this article.

To start Angular application, type ng serve:

Image 3

For the backend, register micro-services in Discovery.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <Discovery>
    <Services>
      <ReportService Source="Config" Hosts="localhost:80" />
      <AuthService Source="Config" Hosts="localhost:81" />
      
      <!--<ReportService Source="Config" 
           Hosts="timetracker-reportservice.azurewebsites.net:80" />
      <AuthService Source="Config" 
       Hosts="timetracker-authservice.azurewebsites.net:80" />-->
    </Services>
  </Discovery>
</configuration>

This is how micro-services are integrated to ASP.NET Core (Startup.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddSwaggerGen(c =>
    {
        ...
    });

    services.AddCors(options =>
    {
        ...
    });

    services.AddTransient((o) => StandardKernel.Get<IReportService>());
    services.AddTransient((o) => StandardKernel.Get<IAuthService>());
}

Inject remote service to the backend API code in API Gateway:

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ReportsController : ControllerBase
{
    private IReportService _reportService;

    public ReportsController(IReportService reportService)
    {
        _reportService = reportService;
    }

    // GET: api/Reports
    [HttpGet]
    [Route("MonthlyReportByUser")]
    public async Task<DailyTimeByUser[]> GetMonthlyReportByUser()
    {
        var token = await this.HttpContext.GetTokenAsync("access_token");
        return await _reportService.GetMonthlyReportByUserAsync(token);
    }
}

To start backend API Gateway and micro-services at local, just run these projects in Visual Studio 2019:

Image 4

Here is how it works:

Image 5

Finally, after login to demo users, this is how the application looks like:

Image 6

Points of Interest

Online demo can be found at https://quinvit.z23.web.core.windows.net/.

You can use sample users:

  • dev0001@quioutlookcom.onmicrosoft.com/HVN@Welc0meHVN@Welc0me
  • dev0002@quioutlookcom.onmicrosoft.com/HVN@Welc0meHVN@Welc0me

After login, click on Timesheet menu to retrieve data from server. Here is the data flow: Angular application -> API Gateway -> ReportService (to retrieve fake report data) -> AuthService (to fullfill user name and email for report data).

History

This first version is for explaining the architecture and service integration part only. In the next version, I will focus more on making a real application with persistent data.

The database access and Register feature to demo auto-register user in Azure Active Directory is coming soon.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Quí Nguyễn NT
Technical Lead
Vietnam Vietnam
Learning IT Technology since 2001, I get started with C++ from 2003. I switch to C# and.NET framework since 2004. Now I am a NodeJS / .NET Core programmer on Azure.

Comments and Discussions

 
-- There are no messages in this forum --
Tip/Trick
Posted 12 Sep 2019

Stats

1.2K views
3 bookmarked