Click here to Skip to main content
13,195,710 members (56,028 online)
Click here to Skip to main content
Add your own
alternative version

Stats

283.1K views
421 bookmarked
Posted 19 Oct 2016

Single Page Application (SPA) for Enterprise App (Angular2 & WebApi) - Part 1 - Overview

, 2 Aug 2017
Rate this:
Please Sign up or sign in to vote.
How to build the SPA for enterprise application using Angular2 and WebApi (RESTful)

Other Articles in the series

  1. Overview
  2. Add new Permission
  3. Project structure
  4. Multi-Languages (i18n)
  5. DI & IoC - Why and Why not?
  6. RESTful & WebApi
  7. Manage Application Lifecycle
  8. Build & Deploy Application
  9. New version of TinyERP with Angular 2 (typescript)
  10. CQRS: Avoiding performance issues in enterprise app (part 1)
  11. Multiple data-stores: Scale your repository (Part 1)
  12. Multiple data-stores: Scale your repository (Part 2)
  13. Basic authentication (user name/ password) with OWIN
  14. Token based authorization with OWIN
  15. Refactoring the architecture/ pattern (Part 1)

Introduction

Note: In my series of this article, I use free template at https://colorlib.com/polygon/gentelella

The first thing, I would like to share to you is "We did not learn technogies, we learn how to use technologies for our business".

Note: In this code, we use Relase Candidate version of Angular 2. New release using angular 2 will be released in this month (April 2017). Hopefully next 2 weeks.

For the new version of TinyERP using offical version of angular, Please visit: https://www.codeproject.com/Articles/1183727/TinyERP-New-version-with-Angular-is-available

Nowadays, with growing of web development, more and more desktop applications (such as HRM, CRM, Payroll, ...)  were migrated to web application.

So the web application can utilize much benefit from web environment. This is easy to search the pros and cons between web application and desktop application on the internet, so we will not discuss here.

Purpose of series of articles will introduce you how did I organise the project for those types of application.

Some highlight technologies:

  • Angular2 (typescript)
  • WebApi (RESTful)
  • Entity Framework
  • Bootstrap
  • IoC
  • Multi-Layer architecture
  • Modular your Application
  • Multi Languages
  • Design Pattern (Unit Of Work, Repository, …)
  • SOLID principle
  • Gulp
  • NodeJs

There are many mistake and improvements need to be done so far.

How to get the code

Checkout the code at https://github.com/techcoaching/TinyERP.git

How to run the code

The code was organized in 2 folders:

  • Client: this is client code written by typescript using angular2 framework.
  • Api: this is server side code where handles request from client.

Run client side:

  1. To run the client side code, please check and install if missing:
  1. Run the app

- Open command prompt and go to the root folder of client:

- Type “npm install” for installing missing nodejs packages.

- Use “npm start” to run the app:

Output in console:

Output on the browser:

To this point, we can run the client successfully

Run API

- For the first run, We need to update the connectionstring in app.common\configurations\configuration.(debug|release).config

- Open Api project in visual studio (2015).

- Press f5 to run the Api on IIS Express, we will see the output on browser:

Config the default route, will remove this error page.

The First Look At The App

- We need to login before continueing:

- Login with tu.tran@yahoo.com/123456, we will see the default page as below (this can be changed in application configuration):

 

List of Roles Page

In this section, we will go through how we implement new page using my code.

Analyse

As my habit, I analyse the page before implement, this will help us recognise:

  • Listing out The steps we need to do to complete the page.
  • Figure out the missing information, so we can ask for help immediatedly.
  • Think about the flow of logic from the client to server side, from UI to repository. So the written code will be nicer. For this, many of my co-workers, they try to write the code first, and debug it after that. When something wrong, it changes your behavior, and we try to change the code to make it works. this may break the logic flow and the code is not follow the convention, architecture was used in the app. This will raise some new potential issues in the future and the code is hard for manteance.

After analysing the page, we figure out the list of things need to be completed as below:

On client:

+ Create new module (called security), I will discusss more pros and cons on how to modular the application.

+ Register route for Roles component (page in angular was called component) and appropriated menu item information (sub menu on th eleft panel)

+ Import and register this setting module with application config.

+ Create component files (html file for UI, ts file for logic handling and ts for view model of that component).

+ Implemnet the UI of Roles component

+ Implement logic of Roles component (also calling to server and getting data)

+ Implement service for this page (service willmake the call to REST api for getting the list of permission).

On Api:

+ Add new controller called RolesController for handling request related to Role.

+ Add RoleService and RoleRepository for getting the list of Roles (I use multi-layers architecture in this case)

+ Add entity into appropriated DbContext.

Ok, Now we will go through step by step in detail.

Implement client

In this section, <root> folder is the folder of client code (the path to "client" folder).

  1. Create new module (called security). as the convention of the app, we create new module.ts file in "<root>/app/modules/secutiry/_share/config" as photo below:

and route.ts file

In this file, we will provide the setting information for security module, such as: list of sub menu items, routing in module, ...

  1. Register route for Roles component (page in angular was called component) and appropriated menu item information (sub menu on th eleft panel). Add this line into the module.ts file created in above step.

  1. Import and register this setting module with application config. This will register the security module in the application, show the module and its sub menu items will be displayed on the left panel.

The sytem will auto register routes in security module for us automaticly.

  1. Create component files (html file for UI, ts file for logic handling and ts for view model of that component).

  1. Implemnet the UI of Roles component, there are some directives already created, we use in this article. I will explain more detail in other article how to implement those directives in other articles.

In this html, we use:

  • "grid" directive, for displaying the list of roles. there are some events we can passnig the handlers and  columns of grid in mode.options property.
  • "page-action" directive, this will dispaly the "Add Role" on the list of Roles as photo below:

  • page, page-header, page-content directives, this is the structure of the page in my framework.
  1. Implement logic of Roles component (also calling to server and getting data)

For declare new componnet we need to:

  • Specify the template file for the component (line 9).
  • Declare the number of directives were used in component html file (line 11). Is the directive was not declare here, it will not be redered in roles.html file and angular will consider its tag (<page-action/>, <grid />) as html tag
  • Declare new Roles class inherit  from BasePage.
  • Declare the model for the component. each component should have its own view model, this help us reducing the complexity of roles.ts file.
  • Getting data from api by calling appropriated method of roleService. We move this to service and let the roles.ts focus on the behavior of the page.

Note: we pass i18nHelper into constructor of RolesModel. this will be used for resolving the lable of grid columns base on the current languages (multi-language supported).

  1. Implement service for this page (service willmake the call to REST api for getting the list of permission).

This is just a simple call to REST api for getting the list of roles. For more information about IConnection, see <root>/app/common/connectors/RESTConnector.ts

Implement Api

In this section, <root> folder is the folder of api code (the path to "api" folder).

  1. Api project structure:

  • App.Common: this contains the common code can be used everywhere in the app
  • App.Api: this is public REST api that client side can call.
  • App.Service: this contains all service interfaces and its appropriated DTOs.
  • App.Service.Impl: this only contains implementation of appropriated interface in App.Service.
  • App.Repository: this contains all repository interfaces. Each repository only operates on 1 entity in database.
  • App.Repository.Impl: this only contains implementation of appropriated interface in App.Resitory.
  • App.Entity: This contains all entities of the app.
  • App.Context: Currently, this containts the all DbContexts in the app, as we use EF framework. I intend to merge this with the App.Entity in the future.

Note: The communication between the layer (such as: App.Api -> App.Service => App.Repository), we use the interface only.

 

  1. Add new controller called RolesController for handling request related to Role.

As the convention of the app, we create new RolesController in "App.Api/Features/Security"

namespace App.Api.Features.Security
{
    [RoutePrefix("api/roles")]
    public class RolesController : ApiController
    {
        [HttpGet]
        [Route("")]
        public IResponseData<IList<RoleListItemSummary>> GetRoles()
        {
            IResponseData<IList<RoleListItemSummary>> response = new ResponseData<IList<RoleListItemSummary>>();
            try
            {
                IRoleService roleService = IoC.Container.Resolve<IRoleService>();
                IList<RoleListItemSummary> roles=roleService.GetRoles();
                response.SetData(roles);
            }
            catch (ValidationException ex)
            {
                response.SetErrors(ex.Errors);
                response.SetStatus(System.Net.HttpStatusCode.PreconditionFailed);
            }
            return response;
        }
    }
}

I think the code is rather simple. From controller we call "GetRoles" of the appropriated service interface and get the list of roles (dto).

IoC will return the concrete instance of that service.

In App.Service.Impl, we have boostrap.cs file, this is the place for registering the service interface and its concrete implementation.

namespace App.Service.Impl
{
    public class Bootstrap : App.Common.Tasks.BaseTask<IBaseContainer>, IBootstrapper
    {
        public Bootstrap():base(App.Common.ApplicationType.All)
        {
        }
        public void Execute(IBaseContainer context)
        {
            context.RegisterSingleton<App.Service.Security.IRoleService, App.Service.Impl.Security.RoleService>();
        }
    }
}
  1. Add IRoleService and RoleService for getting the list of Roles (I use multi-layers architecture in this case)
namespace App.Service.Security
{
    public interface IRoleService
    {
        System.Collections.Generic.IList<RoleListItemSummary> GetRoles();
    }
}

namespace App.Service.Impl.Security
{
    internal class RoleService : IRoleService
    {
        public IList<RoleListItemSummary> GetRoles()
        {
            IRoleRepository repository = IoC.Container.Resolve<IRoleRepository>();
            return repository.GetItems<RoleListItemSummary>();
        }
    }
}

Note:

  • We should define appropriate DTOs for each action, as most cases, we just get some properties of entity and this will help the code easier for mantaince in future.
  • The RoleService class was delared as internal, not a public class. So outside of this dll can not create instance of this class

 

  1. Add IRoleRepository and RoleRepository for getting the list of Roles
namespace App.Repository.Secutiry
{
    public interface IRoleRepository: App.Common.Data.IBaseContentRepository<Role>
    {
    }
}

namespace App.Repository.Impl.Security
{
    internal class RoleRepository: BaseContentRepository<Role>, IRoleRepository
    {
        public RoleRepository() : base(new App.Context.AppDbContext(App.Common.IOMode.Read))
        {
        }

        public RoleRepository(IUnitOfWork uow) : base(uow.Context as IMSSQLDbContext)
        {
        }
    }
}

Note: The same as RoleService, RoleRepository class also was delared as internal. So only the interface can be used outside of this project.

  1. Add entity into appropriated DbContext:
namespace App.Entity.Security
{
    public class Role:BaseContent
    {
        public IList<Permission> Permissions { get; set; }
        public Role():base()
        {
            this.Permissions = new List<Permission>();
        }
        public Role(string name, string desc, IList<Permission> permissions): this() {
            this.Name = name;
            this.Key = App.Common.Helpers.UtilHelper.ToKey(name);
            this.Description = desc;
            if (permissions == null) { return; }
            this.Permissions = permissions;
        }
    }
}

namespace App.Context
{
    public class AppDbContext : App.Common.Data.MSSQL.MSSQLDbContext
    {
        public AppDbContext(IOMode mode = IOMode.Read) : base(new App.Common.Data.MSSQL.MSSQLConnectionString(), mode)
        {
        }
        public System.Data.Entity.DbSet<Role> Roles { get; set; }
    }
}
For more information about Angular, Please have a look at Angular2 - Overview

Summary

In this article, I provider you an overview about how to get the list of roles and display them on the ui.

In next article, we continue with how to create and update roles, and go  into more detail of framework (such as: project structure, directives, ....).

For more information about:

License

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

Share

About the Author

tranthanhtu.vn
Architect
Vietnam Vietnam
I have more than 8 years in web development for multiple types of applications (ERP, Education System, ...).
I usually organize training/ coaching on specified topic (such as: RESTful/ WebApi, Angular2, BEM, LESS, SASS, EF, NodeJs ....). Please contact me on Skype (tranthanhtu83) or email (contact@tranthanhtu.vn) if need.
For more information about me, Please visit http://www.tranthanhtu.vn/page/about-me

You may also be interested in...

Comments and Discussions

 
QuestionMessage Closed Pin
8-Oct-17 20:47
memberjohnwiliam8-Oct-17 20:47 
SuggestionMessage Closed Pin
6-Oct-17 3:03
memberMember 118351786-Oct-17 3:03 
QuestionThanks Sharing Pin
Mamatogel17-Sep-17 20:55
memberMamatogel17-Sep-17 20:55 
AnswerRe: Thanks Sharing Pin
tranthanhtu.vn21-Sep-17 0:31
professionaltranthanhtu.vn21-Sep-17 0:31 
QuestionBundle Pin
Member 407528912-Sep-17 10:40
memberMember 407528912-Sep-17 10:40 
QuestionAuthService Pin
Member 407528925-Aug-17 12:06
memberMember 407528925-Aug-17 12:06 
AnswerRe: AuthService Pin
tranthanhtu.vn26-Aug-17 0:36
professionaltranthanhtu.vn26-Aug-17 0:36 
GeneralRe: AuthService Pin
Member 407528926-Aug-17 4:10
memberMember 407528926-Aug-17 4:10 
AnswerRe: AuthService Pin
tranthanhtu.vn26-Aug-17 19:42
professionaltranthanhtu.vn26-Aug-17 19:42 
GeneralRe: AuthService Pin
Member 407528929-Aug-17 3:43
memberMember 407528929-Aug-17 3:43 
AnswerRe: AuthService Pin
tranthanhtu.vn29-Aug-17 18:34
professionaltranthanhtu.vn29-Aug-17 18:34 
GeneralRe: AuthService Pin
Member 407528929-Aug-17 20:53
memberMember 407528929-Aug-17 20:53 
AnswerRe: AuthService Pin
tranthanhtu.vn29-Aug-17 21:08
professionaltranthanhtu.vn29-Aug-17 21:08 
Questionlogin page Pin
Member 407528911-Aug-17 22:39
memberMember 407528911-Aug-17 22:39 
AnswerRe: login page Pin
tranthanhtu.vn15-Aug-17 3:41
professionaltranthanhtu.vn15-Aug-17 3:41 
Questionpopover Pin
Member 407528911-Aug-17 4:04
memberMember 407528911-Aug-17 4:04 
AnswerRe: popover Pin
tranthanhtu.vn15-Aug-17 3:40
professionaltranthanhtu.vn15-Aug-17 3:40 
GeneralRe: popover Pin
Member 407528915-Aug-17 4:12
memberMember 407528915-Aug-17 4:12 
AnswerRe: popover Pin
tranthanhtu.vn16-Aug-17 19:42
professionaltranthanhtu.vn16-Aug-17 19:42 
QuestionRelease mode Pin
Member 40752899-Aug-17 7:23
memberMember 40752899-Aug-17 7:23 
AnswerRe: Release mode Pin
tranthanhtu.vn9-Aug-17 19:33
professionaltranthanhtu.vn9-Aug-17 19:33 
QuestionNode.js Pin
MP3Mike15-Jun-17 14:05
memberMP3Mike15-Jun-17 14:05 
AnswerRe: Node.js Pin
tranthanhtu.vn15-Jun-17 20:28
professionaltranthanhtu.vn15-Jun-17 20:28 
GeneralMy vote of 5 Pin
EvelineGarde21-May-17 3:19
memberEvelineGarde21-May-17 3:19 
AnswerRe: My vote of 5 Pin
tranthanhtu.vn21-May-17 3:40
professionaltranthanhtu.vn21-May-17 3:40 
GeneralMy vote of 4 Pin
Terrance Duong18-May-17 0:45
memberTerrance Duong18-May-17 0:45 
AnswerRe: My vote of 4 Pin
tranthanhtu.vn18-May-17 0:57
professionaltranthanhtu.vn18-May-17 0:57 
QuestionLink broken Pin
Member 1199850026-Apr-17 7:40
memberMember 1199850026-Apr-17 7:40 
AnswerRe: Link broken Pin
tranthanhtu.vn26-Apr-17 13:21
professionaltranthanhtu.vn26-Apr-17 13:21 
GeneralMy vote of 4 Pin
Bob Delaney14-Mar-17 11:39
memberBob Delaney14-Mar-17 11:39 
AnswerRe: My vote of 4 Pin
tranthanhtu.vn15-Mar-17 0:46
professionaltranthanhtu.vn15-Mar-17 0:46 
Questionfunction createModule() loads misspelt module "app/modules/secutiry" Pin
Member 130130346-Mar-17 7:57
memberMember 130130346-Mar-17 7:57 
AnswerRe: function createModule() loads misspelt module "app/modules/secutiry" Pin
tranthanhtu.vn6-Mar-17 17:31
professionaltranthanhtu.vn6-Mar-17 17:31 
QuestionHow to implement Authorization on controllers. Pin
M Z K3-Mar-17 1:42
memberM Z K3-Mar-17 1:42 
AnswerRe: How to implement Authorization on controllers. Pin
tranthanhtu.vn4-Mar-17 19:20
professionaltranthanhtu.vn4-Mar-17 19:20 
AnswerMessage Closed Pin
16-Jun-17 0:21
memberjohnwiliam16-Jun-17 0:21 
AnswerRe: How to implement Authorization on controllers. Pin
tranthanhtu.vn16-Jun-17 23:27
professionaltranthanhtu.vn16-Jun-17 23:27 
QuestionDatabase Isseu Pin
M Z K16-Feb-17 23:12
memberM Z K16-Feb-17 23:12 
AnswerRe: Database Isseu Pin
tranthanhtu.vn17-Feb-17 0:54
professionaltranthanhtu.vn17-Feb-17 0:54 
Questionclient login page doesn't appear Pin
Larry @Datasmith13-Feb-17 16:45
memberLarry @Datasmith13-Feb-17 16:45 
AnswerRe: client login page doesn't appear Pin
tranthanhtu.vn13-Feb-17 18:39
professionaltranthanhtu.vn13-Feb-17 18:39 
QuestionNice Article :) . Can we not use Visual Studio 2015 for Angular2 project Pin
NaibedyaKar19-Jan-17 23:30
professionalNaibedyaKar19-Jan-17 23:30 
AnswerRe: Nice Article :) . Can we not use Visual Studio 2015 for Angular2 project Pin
tranthanhtu.vn19-Jan-17 23:42
professionaltranthanhtu.vn19-Jan-17 23:42 
GeneralRe: Nice Article :) . Can we not use Visual Studio 2015 for Angular2 project Pin
NaibedyaKar20-Jan-17 0:00
professionalNaibedyaKar20-Jan-17 0:00 
AnswerRe: Nice Article :) . Can we not use Visual Studio 2015 for Angular2 project Pin
tranthanhtu.vn20-Jan-17 0:37
professionaltranthanhtu.vn20-Jan-17 0:37 
QuestionGreat article Pin
Member 1292169419-Jan-17 21:05
memberMember 1292169419-Jan-17 21:05 
AnswerRe: Great article Pin
tranthanhtu.vn19-Jan-17 21:11
professionaltranthanhtu.vn19-Jan-17 21:11 
QuestionUpgrade Pin
Member 85690513-Jan-17 5:09
memberMember 85690513-Jan-17 5:09 
AnswerRe: Upgrade Pin
tranthanhtu.vn13-Jan-17 5:13
professionaltranthanhtu.vn13-Jan-17 5:13 
QuestionGET http://localhost:3000/bundle.js [HTTP/1.1 404 Not Found 3ms] Pin
DannyJooste7-Jan-17 21:43
memberDannyJooste7-Jan-17 21:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171019.1 | Last Updated 3 Aug 2017
Article Copyright 2016 by tranthanhtu.vn
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid