Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Building Role-Based Access Control in Angular Apps

clock June 18, 2025 08:14 by author Peter

Securing components and routes according to user roles is crucial in contemporary online applications. A technique known as role-based access control, or RBAC, permits or prohibits users from accessing specific areas of an application according to the responsibilities they have been allocated. This post will show you how to use role-based logic, services, and route guards to construct RBAC in Angular and manage access throughout your application.

What is RBAC?
Role-Based Access Control is a security mechanism that,

  • Assigns users to roles (like Admin, Editor, User).
  • Defines permissions for each role.
  • Restricts or allows access to routes, components, or actions based on the user’s role.

Prerequisites
Before implementing RBAC, ensure,

  • You have authentication set up (e.g., JWT-based login).
  • Roles are retrievable from the backend or the token.
  • Angular project is initialized with routing (@angular/router).
  • Step-by-Step Implementation

1. Define Roles and User Model
// user.model.ts
export interface User {
  username: string;
  token: string;
  roles: string[]; // e.g., ['Admin', 'User']
}


2. Authentication Service with Role Info

// auth.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private currentUser: User | null = null;

  constructor() {
    const userData = localStorage.getItem('user');
    if (userData) {
      this.currentUser = JSON.parse(userData);
    }
  }

  getUser(): User | null {
    return this.currentUser;
  }

  hasRole(role: string): boolean {
    return this.currentUser?.roles.includes(role) ?? false;
  }

  hasAnyRole(roles: string[]): boolean {
    return roles.some(role => this.hasRole(role));
  }
}


3. Create a Role Guard

// role.guard.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class RoleGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const expectedRoles = route.data['roles'] as string[];
    if (this.authService.hasAnyRole(expectedRoles)) {
      return true;
    }

    // Redirect to access denied or login
    this.router.navigate(['/access-denied']);
    return false;
  }
}


4. Use the Role Guard in Routes

// app-routing.module.ts
const routes: Routes = [
  {
    path: 'admin',
    component: AdminDashboardComponent,
    canActivate: [RoleGuard],
    data: { roles: ['Admin'] }
  },
  {
    path: 'editor',
    component: EditorComponent,
    canActivate: [RoleGuard],
    data: { roles: ['Editor', 'Admin'] }
  },
  {
    path: 'access-denied',
    component: AccessDeniedComponent
  }
];


5. Show/Hide UI Based on Roles (Optional)

<!-- in component template -->
<div *ngIf="authService.hasRole('Admin')">
  <button>Edit Settings</button>
</div>


Best Practices for Angular RBAC

  • Always secure routes with guards; never rely solely on front-end UI logic.
  • Store roles securely (e.g., in JWT tokens, not just localStorage).
  • Refresh user roles upon login or token refresh.
  • Keep RBAC logic centralized inside services and guards.
  • Pair RBAC with backend authorization to fully protect APIs.

Conclusion
Implementing RBAC in Angular ensures that your application is secure, maintainable, and scalable. Using route guards, role-aware services, and conditional templates, you can easily control who gets access to what. With this setup, you now have a robust way to protect routes and features based on user roles in your Angular apps. 
Happy coding !!



AngularJS Hosting Europe - HostForLIFE.eu :: Angular Lifecycle Hooks: An Understanding

clock June 13, 2025 08:17 by author Peter

Angular components go through a lifecycle from creation to destruction. Understanding this lifecycle is crucial for writing clean, efficient, and bug-free Angular applications. Angular provides lifecycle hooks that allow developers to tap into these key moments, such as initialization, change detection, and destruction. In this article, we'll explore the most commonly used Angular lifecycle hooks with practical examples and real-world use cases.

What Are Lifecycle Hooks?
Lifecycle hooks are special TypeScript methods that Angular calls automatically at specific points in a component's lifecycle.

They are defined in Angular’s core and include:
    ngOnInit()
    ngOnChanges()
    ngDoCheck()
    ngAfterViewInit()
    ngAfterViewChecked()
    ngAfterContentInit()
    ngAfterContentChecked()
    ngOnDestroy()


1. ngOnChanges()

  • Purpose: Called when any data-bound property (@Input()) changes.
  • Timing: Runs before ngOnInit() and whenever an input changes thereafter.
  • Use Case: Useful when a parent component updates an input value, and the child needs to act on it.

Example
@Input() userId: number;

ngOnChanges(changes: SimpleChanges) {
  if (changes.userId) {
    this.fetchUser(changes.userId.currentValue);
  }
}


2. ngOnInit()

  • Purpose: Called once after the component is initialized.
  • Timing: After the first ngOnChanges().
  • Use Case: Initialize component data (like API calls, default values, subscriptions).

Example
ngOnInit() {
  this.loadDashboardData();
}


3. ngDoCheck()

  • Purpose: Called during every change detection cycle.
  • Timing: After ngOnChanges() and ngOnInit(), and on every change thereafter.
  • Use Case: Custom change detection logic (e.g., detecting changes in deep objects or arrays).

Example
ngDoCheck() {
  if (this.previousLength !== this.items.length) {
    this.previousLength = this.items.length;
    this.onListLengthChanged();
  }
}


Note. Use with caution, as it can lead to performance issues.

4. ngAfterContentInit()

  • Purpose: Called once after Angular projects external content into the component.
  • Timing: After content has been initialized via ng-content.
  • Use Case: Manipulating projected content.

Example
ngAfterContentInit() {
  console.log('Content projected!');
}

5. ngAfterContentChecked()

  • Purpose: Called after every check of the projected content.
  • Timing: After every change detection cycle for ng-content.
  • Use Case: Debugging or Verifying Content Changes.

Example
ngAfterContentChecked() {
  console.log('Projected content checked.');
}

6. ngAfterViewInit()

  • Purpose: Called once after the component’s view (and child views) are initialized.
  • Timing: After Angular sets up the DOM, including @ViewChild queries.
  • Use Case: Interacting with DOM elements.

Example
@ViewChild('inputRef') input: ElementRef;

ngAfterViewInit() {
  this.input.nativeElement.focus(); // Safe to access now
}


7. ngAfterViewChecked()
Purpose: Called after every check of the component’s views.
Timing: After Angular updates the view and child views.
Use Case: Responding to changes in the component’s view (use sparingly).

Example
ngAfterViewChecked() {
  console.log('View checked.');
}


8. ngOnDestroy()

  • Purpose: Called just before Angular destroys the component.
  • Timing: Before component removal from the DOM.
  • Use Case: Cleanup logic like unsubscribing Observables, detaching event listeners, and clearing timers.

Example
subscription: Subscription;

ngOnInit() {
  this.subscription = this.dataService.getData().subscribe(...);
}

ngOnDestroy() {
  this.subscription.unsubscribe(); // Prevent memory leaks
}

Hook Triggered When... Common Use
ngOnChanges Input property changes Respond to input changes
ngOnInit The component is initialized Fetch data, set up
ngDoCheck Every change detection cycle Custom change tracking
ngAfterContentInit External content is projected Handle ng-content
ngAfterContentChecked Projected content checked Debug content projection
ngAfterViewInit Component’s view initialized DOM manipulation
ngAfterViewChecked Component’s view checked View debugging
ngOnDestroy The component is about to be destroyed Cleanup

Best Practices

  • Prefer ngOnInit over constructor() for initialization logic.
  • Always clean up in ngOnDestroy() to prevent memory leaks.
  • Use ngDoCheck and ngAfterViewChecked only when necessary due to performance cost.
  • Keep each lifecycle hook focused, and avoid cluttering with unrelated logic.


Conclusion
Understanding and using Angular’s lifecycle hooks gives you deeper control over your component behavior, especially when dealing with asynchronous data, view rendering, or external libraries.

Whether you’re initializing data, responding to changes, or cleaning up resources, lifecycle hooks help ensure your Angular app remains performant and maintainable.

Happy coding!

 



AngularJS Hosting Europe - HostForLIFE :: How to Include Custom Modules in the ABP.IO Application?

clock June 10, 2025 09:48 by author Peter

If you want to extend your ABP. IO application with a custom module, like Vineforce.Test—this guide is for you. Whether you’re building a new feature or organizing your code into reusable parts, creating a custom module helps keep your application clean, scalable, and maintainable. In this guide, we’ll walk through the full integration process step by step, covering both the backend and the Angular frontend. You’ll learn how to properly register the module, configure dependencies, and connect the UI layer to your logic. By the end, you’ll have a working module that’s fully integrated into your ABP.IO solution, following best practices.

No guesswork, no skipping steps, just a clear path to getting your custom module up and running.

Prerequisites

Step 1. Install ABP CLI
If not already installed, run the following command.
dotnet tool install -g Volo.Abp.Cli

Step 2. Create the main Apb.io application with the name “Vineforce.Admin”
abp new Vineforce.Admin -t app -u angular -m none --separate-auth-server --database-provider ef -csf

It creates the structure of the backend of the main ABP application as follows.

Step 3. Configure appsettings.json of the main ABP.IO
Edit the appsettings.json files in the two projects below to include the correct connection strings.

Projects

  • Vineforce.Admin.HttpApi.Host
  • Vineforce.Admin.DbMigrator

Step 4. Create the Module folder in the main application as Follow the official guide to create your module.

If you choose Angular as the UI framework (by using the -u angular option), the generated solution will include a folder named angular. This folder contains all the client-side code for the application.

Example: A module named Vineforce.Test was created using the Angular UI option.

Step 1. When you open the Angular folder in an IDE, the folder structure will appear as follows.

Step 2. And the backend structure is as follows.

Step 3. Configure appsettings.json.

Edit the appsettings.json file in the Host projects to include the correct connection strings.

Projects
    Vineforce.Test.AuthServer
    Vineforce.Test.HttpApi.Host
    Vineforce.Test.Web.Unified

"ConnectionStrings": { "Default": "Server=servername;Database=Test_Main;Trusted_Connection=True;TrustServerCertificate=True", "Test": "Server=VINEFORCE-SHIVA;Database=Test_Module;Trusted_Connection=True;TrustServerCertificate=True" }


Make sure the server names and database details match your development environment.

Step 4. Apply Database Update.
In the Package Manager Console (under the EntityFrameworkCore project), run.

Update-Database

Step 5. Run the Application.
Set Vineforce.Test.Web.Unified as the startup project and launch the application using the default credentials.
    Username: admin
    Password: 1q2w3E*


Step 6. Ensure Redis Is Running.
Redis is used for distributed caching. Make sure Redis is installed and running before starting the application.

Step 7. Application Startup Order.
Run the following projects in order
*.AuthServer or *.IdentityServer
*.HttpApi.Host
*.Web.Unified


Step 8. Adding a Module to the Backend of the Main Application.
cd C:\Users\Vineforce\source\repos\AbpAdmin

Step 9. Add All Required Projects of the module to the Main ABP.IO Solution.

To include various parts of your module (such as Domain, Application, EntityFrameworkCore, and HttpApi) in the main ABP solution, run the following commands.
dotnet sln add modules\vineforce.test\src\Vineforce.Test.Domain\Vineforce.Test.Domain.csproj
dotnet sln add modules\vineforce.test\src\Vineforce.Test.Application\Vineforce.Test.Application.csproj
dotnet sln add modules\vineforce.test\src\Vineforce.Test.EntityFrameworkCore\Vineforce.Test.EntityFrameworkCore.csproj
dotnet sln add modules\vineforce.test\src\Vineforce.Test.HttpApi\Vineforce.Test.HttpApi.csproj


Projects are added as follows.

Add Project References Using Visual Studio
In the Vineforce.Admin.HttpApi.Host project: Right-click the project and select “Add” → “Project Reference”.

Step 1. In the dialog that appears, check the following projects.
    Vineforce.Test.Application
    Vineforce.Test.EntityFrameworkCore
    Vineforce.Test.HttpApi

Step 2. Click OK to confirm and add the references.

Step 3. After adding the project > reference, here you can add all module references you want.

 

Register Module Dependencies in AdminHttpApiHostModule.cs.
In AdminHttpApiHostModule.cs, update the [DependsOn(...)] attribute:.

typeof(TestHttpApiModule),
typeof(TestApplicationModule),
typeof(TestEntityFrameworkCoreModule),
typeof(TestDomainSharedModule)


Also, add the necessary using statements.
using Vineforce.Test;
using Vineforce.Test.EntityFrameworkCore;

Configure the Module in the EntityFrameworkCore Project
To ensure that schema, table mappings, and other Entity Framework configurations from the module are applied in the main ABP.IO application, follow these steps.

Add a Project Reference.

  • Right-click on the Vineforce.Admin.EntityFrameworkCore project.
  • Select Add → Project Reference.
  • Check and add: Vineforce.Test.EntityFrameworkCore

Update the DbContext Configuration

  • Open AdminDbContext.cs.
  • Inside the OnModelCreating method, add the following line to apply the module’s configuration.

builder.ConfigureTest();

You can verify this by navigating to Vineforce.Test.The EntityFrameworkCore module and opening the TestDbContext class.

Apply Migrations to Update the Database Schema
After completing the integration steps, you need to apply Entity Framework migrations to reflect the module’s schema changes in the database.

Option 1. Using PowerShell or Terminal.
Open a PowerShell or terminal window.
Navigate to the EntityFrameworkCore project directory of your main application, for example:cd src/Vineforce.Admin.EntityFrameworkCore.
Run the following command to create a new migration.
dotnet ef migrations add Add_Test_Module

Option 2. Using the Package Manager Console in Visual Studio.

  • Open the Package Manager Console (Tools → NuGet Package Manager → Package Manager Console).
  • Set the Default Project to src\Vineforce.Admin.EntityFrameworkCore.
  • Run the following command.

PM> Add-Migration Add_Test_Module

This will generate a new migration that includes all Entity Framework changes from the integrated module.

Then run the following command to apply the migration and update the database.
Update-Database

Steps to add the module application to the main ABP.IO application
Step 1. Build the Angular Module.
Navigate to the module’s frontend directory and build the module using the Angular CLI.
ng build test --configuration production

This command compiles the test Angular module in production mode and outputs the build artifacts to the dist folder.

Output folder: C:\Users\Vineforce\source\repos\AbpAdmin\modules\Vineforce.Test\angular\dist

Step 2. Copy Module Output to Main App.
Go to your main app’s angular folder: C:\Users\Vineforce\source\repos\AbpAdmin\angular
Create a project folder inside it.
Copy the test folder from the dist directory into the projects.
Final path: C:\Users\Vineforce\source\repos\AbpAdmin\angular\projects\test

Step 3. Update App Routing.
Open app-routing.module.ts in the main app
C:\Users\Vineforce\source\repos\AbpAdmin\angular\src\app\app-routing.module.ts.

In app-routing.module.ts, import the module’s routing configuration and add it to the main route definitions.
{
  path: 'test',
  loadChildren: () =>
    import('test').then(m => m.TestModule.forLazy())
}


Step 4. Link the Module in package.json
Open the package.json file having path C:\Users\Vineforce\source\repos\AbpAdmin\angular add the following line under the “dependencies” section to link your local module.
"test": "file:projects/test"

Then install dependencies.
npm install

You can now see the Test Module API controller in the Swagger UI of the main application.

You can now log in to the main application. The Test module now appears in the main application. You can add, edit, or delete items according to the assigned permissions.

Country ‘Russia’ has been added. You can view, edit, or delete it on the page.

You can grant or revoke permission on the following page.

Now, Edit permission has been disabled for the current user/page.

Currently, the delete option is visible, but the edit option is not showing on the pagepermission has been disabled for the current user/page.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in