How to migrate AngularJS routing to Angular Router

Loading

Migrating from AngularJS (1.x) to Angular (2+) involves several important changes, especially in how routing is handled. AngularJS uses the $routeProvider for routing, while Angular uses the @angular/router package to provide a more advanced and flexible routing mechanism.

The migration process generally requires replacing AngularJS routing configuration with Angular’s RouterModule, which provides powerful features like lazy loading, guards, and more. Here’s a step-by-step guide on how to migrate AngularJS routing to Angular Router.


1. Overview of AngularJS Routing and Angular Router

AngularJS Routing

In AngularJS, routing is typically done using the ngRoute module, which provides the $routeProvider to configure routes.

Example of routing in AngularJS:

angular.module('app', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
});

Angular Router

In Angular, routing is handled through the RouterModule. You define routes in the AppRoutingModule (or a specific routing module) and set up navigation using path-based routes.

Example of routing in Angular:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}

2. Migration Process: Step-by-Step Guide

Step 1: Set Up Angular Router in Your Application

  1. Install Angular Router: If not already installed, you need to import Angular Router in your application module. bashCopyEditnpm install @angular/router --save
  2. Import RouterModule: In your app.module.ts (or core module), import RouterModule and set up routing.
    import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; // Import RouterModule import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { AppRoutingModule } from './app-routing.module'; // Import your routing module @NgModule({ declarations: [AppComponent, HomeComponent, AboutComponent], imports: [BrowserModule, AppRoutingModule], // Add AppRoutingModule here bootstrap: [AppComponent] }) export class AppModule {}
  3. Create AppRoutingModule: You’ll need a separate routing module to handle your application’s routes. This file will configure the routing and export the RouterModule for use in the app.
    import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}

Step 2: Migrate Routes from AngularJS to Angular

Now, let’s migrate routes from AngularJS to Angular. Here’s how to migrate each element:

1. Route Configuration

In AngularJS, routes were configured using $routeProvider. In Angular, routes are configured using the RouterModule.

AngularJS Example:

$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});

Angular Example:

const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
  • Replace templateUrl with component.
  • Replace controllers with components.
  • Angular uses a component-based architecture, so instead of controllers, you define components.
2. Route Parameters

In AngularJS, route parameters were retrieved via $routeParams. In Angular, route parameters can be accessed using ActivatedRoute.

AngularJS Example:

$routeProvider
.when('/user/:id', {
templateUrl: 'user.html',
controller: 'UserController'
});

Angular Example:

import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-user',
templateUrl: './user.component.html',
})
export class UserComponent implements OnInit {
userId: string;

constructor(private route: ActivatedRoute) {}

ngOnInit(): void {
this.userId = this.route.snapshot.paramMap.get('id');
}
}
  • In Angular, use ActivatedRoute to access route parameters.
3. Redirects and Wildcard Routes

Angular supports wildcard routes to handle 404 pages (similar to otherwise in AngularJS).

AngularJS Example:

$routeProvider
.otherwise({
redirectTo: '/home'
});

Angular Example:

const routes: Routes = [
{ path: '**', redirectTo: '/home' } // Wildcard for 404
];
4. Route Guards

Angular provides a powerful mechanism to protect routes using route guards. In AngularJS, this could be done with resolve or custom logic.

AngularJS Example:

$routeProvider
.when('/admin', {
templateUrl: 'admin.html',
controller: 'AdminController',
resolve: {
user: function(AuthService) {
return AuthService.checkLogin();
}
}
});

Angular Example:

import { CanActivate } from '@angular/router';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}

canActivate(): boolean {
return this.authService.isAuthenticated();
}
}

const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
];
  • In Angular, you use CanActivate guards to check authentication or other conditions before accessing a route.

3. Migrating AngularJS Components to Angular

In AngularJS, you use directives and controllers to define your views. In Angular, everything is handled by components.

Example of AngularJS Component:

angular.module('app')
.controller('HomeController', function() {
this.message = 'Welcome to Home';
});

Migrating to Angular Component:

import { Component } from '@angular/core';

@Component({
selector: 'app-home',
template: `<h1>{{ message }}</h1>`,
})
export class HomeComponent {
message = 'Welcome to Home';
}

Here’s the migration flow:

  • Replace controllers with components.
  • Use template instead of templateUrl.
  • Bind data using class properties and interpolation.

Leave a Reply

Your email address will not be published. Required fields are marked *