All About Routing In Angular Applications

In this article about routing in Angular applications, I will cover routing from scratch to in-depth details. I will start from how routing works in Angular and then we will dive deeper with routing. Below are some use cases:

  • How does routing work? (Creating routing from scratch)
  • How to deal with wildcard characters? ( Not Found Routes)
  • How to display the current page as active on the menu bar? (routerLinkActive)
  • How to Guard Routes? (canActivate)
  • How to store redirectURL and navigate to the same URL after a successful login?
  • Child Routing?
  • How to display login and logout button conditionally?
  • How to display a spinner/progress bar using routing? (resolver)
  • How to make routing, case insensitive?
  • And many more…

At the end of the article, you will have in-depth knowledge of Routing in Angular applications.

So, as we will be focusing only on routing, we will not go in details with any other topics like how to fetch data through HTTP client and how to create services.

So, I had already created the project and directory structure which is shown below.

All About Routing In Angular Application 

I already created product, home, user and header component as shown in the directory structure. Now to begin with, we will see how routing works.

I will divide the routing process into 4 steps.

Create the routes array

I will create a separate routing file and name it as app.routing.ts

  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './home/home.component';  
  3. import { LoginComponent } from './Users/login/login.component';  
  4. import { ProductListComponent } from './Products/product-list/product-list.component';  
  5. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  6. const arr: Routes = [  
  7.  {path: '', redirectTo: '/home', pathMatch: 'full'},  
  8.  {path: 'home', component: HomeComponent},  
  9.  {path: 'login', component: LoginComponent},  
  10.  {path:'products', component: ProductListComponent },  
  11.  {path:'addproduct/:id', component: ProductAddComponent }  
  12. ];  
  13.   
  14.  export const routing = RouterModule.forRoot(arr);  

So when we request http://localhost:4200/products, it will check for the path of “ products” in our routing array, and if it finds that particular path it will display the corresponding component accordingly.

I had created an array of routes and I have declared that array as a root route or parent route. And I am exporting the root route so that we can import it on app.module.ts file

Import routes array in app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5. import { routing } from './app.routing';  
  6. import { HttpClientModule } from '@angular/common/http';  
  7. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  8. import { LoginComponent } from './Users/login/login.component';  
  9. import { HomeComponent } from './home/home.component';  
  10. import { HeaderComponent } from './header.component';  
  11. import { ProductListComponent } from './Products/product-list/product-list.component';  
  12. @NgModule({  
  13.   declarations: [  
  14.     AppComponent,  
  15.     ProductAddComponent,  
  16.     LoginComponent,  
  17.     HomeComponent,  
  18.     HeaderComponent,  
  19.     ProductListComponent  
  20.   ],  
  21.   imports: [  
  22.     BrowserModule,  
  23.     FormsModule,  
  24.     routing,  
  25.     HttpClientModule  
  26.   ],  
  27.   providers: [],  
  28.   bootstrap: [AppComponent]  
  29. })  
  30. export class AppModule { }  
Create the seperate header.component and replace href => routerLink,
  1. <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;" >  
  2.   <a class="navbar-brand" routerLink="">Routing Application</a>  
  3.   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  4.     <span class="navbar-toggler-icon"></span>  
  5.   </button>  
  6.   
  7.   <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  8.     <ul class="navbar-nav mr-auto">  
  9.      <li class="nav-item" >  
  10.         <a class="nav-link" routerLink="/home">Home </a>  
  11.       </li>  
  12.       <li class="nav-item" >  
  13.         <a class="nav-link" routerLink="/products">Products</a>  
  14.       </li>  
  15.       <li class="nav-item" >  
  16.           <a class="nav-link" [routerLink]="['/addproduct',0]">Add Product</a>  
  17.       </li>  
  18.     </ul>  
  19.   </div>  
  20. </nav>  

Here, I am using bootstrap 4 for styling purposes only. And to make routing work in an angular application we will be using routerLink directives instead of href.

So we can use it like,

  1. <a class="nav-link" routerLink="/home">Home </a>  

“/home “ will be the same as we had declared in the routing file.

Use <router-outlet> on app.component.html

Now, replace the app.component.html as shown below,

  1. <app-header></app-header>  
  2. <router-outlet></router-outlet>  

First, it will display menu, i.e. header.component.html and then inside router-outlet it will display the component, which will match with the path, declared in routes array. Say for example if we request http://localhost:4200/ then as per routing array it will display the home.component,

All About Routing In Angular Application 
 
All About Routing In Angular Application
 

How to deal with wildcard characters?

Say for example, a user requests a path/URL which doesn’t match with any path from routing array. We can handle this by simply updating our routes array as shown below,

  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './home/home.component';  
  3. import { LoginComponent } from './Users/login/login.component';  
  4. import { ProductListComponent } from './Products/product-list/product-list.component';  
  5. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  6. import { PageNotFoundComponent } from './page-not-found/page-not-found.component';  
  7.   
  8. const arr: Routes = [  
  9.  {path: '', redirectTo: '/home', pathMatch: 'full'},  
  10.  {path: 'home', component: HomeComponent},  
  11.  {path: 'login', component: LoginComponent},  
  12.  {path:'products', component: ProductListComponent },  
  13.  {path:'addproduct/:id', component: ProductAddComponent },  
  14.  {path: '**', component:PageNotFoundComponent }  
  15. ];  
  16.   
  17.  export const routing = RouterModule.forRoot(arr);  

Here, I have added only one path with “**” this stands for if your URL or path doesn’t match to any path defined in routing array then display page-not-found component. ( like error 404) but the most important thing, the order of path:’**’ must be last only, otherwise if you add ‘**’ path first in routing array then no other routes will work.

All About Routing In Angular Application
 

How to display current menu item selected on the menu bar?

Say, for example, if we are on the home page, then the currently selected menu item should be Home,  and if we navigate to the Products page, then the currently selected menu item should be Products.

We can achieve it by simply writing CSS class for displaying the currently-selected menu item highlighted and then applying that CSS class to your header component, I am using Bootstrap 4, so it comes with pre-built CSS classes, in my case “Active” class is already created, so I am just applying it to my header component as shown below,

  1. <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;" >  
  2.   <a class="navbar-brand" routerLink="">Routing Application</a>  
  3.   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  4.     <span class="navbar-toggler-icon"></span>  
  5.   </button>  
  6.   
  7.   <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  8.     <ul class="navbar-nav mr-auto">  
  9.         <!-- [routerLinkActiveOptions]="{ exact : true}" -->  
  10.       <li class="nav-item" routerLinkActive="active" >  
  11.         <a class="nav-link" routerLink="/home">Home </a>  
  12.       </li>  
  13.       <li class="nav-item" routerLinkActive="active" >  
  14.         <a class="nav-link" routerLink="/products">Products</a>  
  15.       </li>  
  16.       <li class="nav-item" routerLinkActive="active">  
  17.           <a class="nav-link" [routerLink]="['/addproduct',0]">Add Product</a>  
  18.       </li>  
  19.   
  20.     </ul>  
  21.   
  22.   </div>  
  23. </nav>  
All About Routing In Angular Application
 
All About Routing In Angular Application
 
All About Routing In Angular Application 

We can also use [routerLinkActiveOptions]="{ exact : true}",

To match the exact path.

How to store redirectURL and navigate to the same URL after a successful login?

Now, to achive the above said use case, I already have created user-auth service and login component as shown below,

user-auth.services.ts

  1. import { User } from './user';  
  2. import { Injectable } from '@angular/core';  
  3. import { Router } from '@angular/router';  
  4.   
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class UserAuthService {  
  9. currentUser:User;  
  10. redirectURL:string;  
  11.   
  12.   constructor(private _route:Router) { }  
  13.   get isLoggedIn():boolean{  
  14.     return !!this.currentUser;  
  15.   }  
  16.   logIn(username:string,password:string):void {  
  17.     if(username==='admin'){  
  18.       this.currentUser={  
  19.         id:'[email protected]',  
  20.         uname:'admin',  
  21.         isAdmin:true  
  22.       }  
  23.       return;  
  24.     }  
  25.     this.currentUser={  
  26.       id:username+'@gmail.com',  
  27.       uname:username,  
  28.       isAdmin:false  
  29.     }  
  30.   }  
  31.   logout(){  
  32.     this.currentUser=null;  
  33.     this._route.navigate(['/home']);  
  34.   }  
  35. }  

To provide you with an overview of user-auth.service.ts, I had created a login and logout methods, which will validate the user, here I am using some static values, you can replace it with your actual values. I had created an isLoggedIn property to return a Boolean value, it will return true if the user is logged in and false if not logged in. Also, I have created two properties --  current user to store current user credentials and redirectURL to store the path from which user is redirected to the login page so that after being successfully logged in we can navigate user back to actual URL.

login.component.html

  1. <div class="card">  
  2.   <div class="card-header">  
  3.     {{pageTitle}}  
  4.   </div>  
  5.   
  6.   <div class="card-body">  
  7.     <form novalidate  
  8.           (ngSubmit)="login(loginForm)"  
  9.           #loginForm="ngForm"  
  10.           autocomplete="off">  
  11.       <fieldset>  
  12.   
  13.         <div class="form-group row">  
  14.           <label class="col-md-2 col-form-label"  
  15.                  for="userNameId">User Name</label>  
  16.           <div class="col-md-8">  
  17.             <input class="form-control"  
  18.                    id="userNameId"  
  19.                    type="text"  
  20.                    placeholder="User Name (required)"  
  21.                    required  
  22.                    ngModel  
  23.                    name="userName"  
  24.                    #userNameVar="ngModel"  
  25.                    [ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />  
  26.             <span class="invalid-feedback">  
  27.               <span *ngIf="userNameVar.errors?.required">  
  28.                 User name is required.  
  29.               </span>  
  30.             </span>  
  31.           </div>  
  32.         </div>  
  33.   
  34.         <div class="form-group row">  
  35.           <label class="col-md-2 col-form--label"  
  36.                  for="passwordId">Password</label>  
  37.   
  38.           <div class="col-md-8">  
  39.             <input class="form-control"  
  40.                    id="passwordId"  
  41.                    type="password"  
  42.                    placeholder="Password (required)"  
  43.                    required  
  44.                    ngModel  
  45.                    name="password"  
  46.                    #passwordVar="ngModel"  
  47.                    [ngClass]="{'is-invalid': (passwordVar.touched || passwordVar.dirty) && !passwordVar.valid }" />  
  48.             <span class="invalid-feedback">  
  49.               <span *ngIf="passwordVar.errors?.required">  
  50.                 Password is required.  
  51.               </span>  
  52.             </span>  
  53.           </div>  
  54.         </div>  
  55.   
  56.         <div class="row">  
  57.           <div class="col-md-4 offset-md-2">  
  58.             <button class="btn btn-primary mr-3"  
  59.                     type="submit"  
  60.                     style="width:80px"  
  61.                     [disabled]="!loginForm.valid">  
  62.               Log In  
  63.             </button>  
  64.             <button class="btn btn-outline-secondary"  
  65.                     type="button"  
  66.                     style="width:80px"  
  67.                     [routerLink]="['/home']">  
  68.               Cancel  
  69.             </button>  
  70.           </div>  
  71.         </div>  
  72.       </fieldset>  
  73.     </form>  
  74.   </div>  
  75.   
  76.   <div class="alert alert-danger"  
  77.        *ngIf="errorMessage">{{errorMessage}}  
  78.   </div>  
  79. </div>  

login.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { UserAuthService } from '../user-auth.service';  
  3. import { Router } from '@angular/router';  
  4. import { NgForm } from '@angular/forms';  
  5.   
  6. @Component({  
  7.   selector: 'app-login',  
  8.   templateUrl: './login.component.html',  
  9.   styleUrls: ['./login.component.css']  
  10. })  
  11. export class LoginComponent implements OnInit {  
  12.   
  13.   errorMessage: string;  
  14.   pageTitle = 'Log In';  
  15.   
  16.   constructor(private authService: UserAuthService,  
  17.               private router: Router) { }  
  18.   
  19.   login(loginForm: NgForm) {  
  20.     if (loginForm && loginForm.valid) {  
  21.       const userName = loginForm.form.value.userName;  
  22.       const password = loginForm.form.value.password;  
  23.       if(!userName || !password){  
  24.         alert("Please enter Username and Password");  
  25.       }  
  26.       else{  
  27.         this.authService.logIn(userName, password);  
  28.       }  
  29.   
  30.       if (this.authService.redirectURL) {  
  31.         this.router.navigateByUrl(this.authService.redirectURL);  
  32.       } else {  
  33.         this.router.navigate(['/products']);  
  34.       }  
  35.     } else {  
  36.       this.errorMessage = 'Please enter a user name and password.';  
  37.     }  
  38.   }  
  39.   ngOnInit(){}  
  40.   
  41. }  

So, now here if the user is successfully validated, then we will also check for the redirectURL property of user-auth services, if it is empty then by default we will redirect the user to the product list page and if there is a value in the redirectURL property, we will redirect the user to the actual URL.

How to display login and logout button conditionally?

In order to display login and logout button conditionally; i.e. if the user is logged in then display Logout button and if the user is not logged in then display Login button. To do so we need to update the header component as shown below,

Header.component.html

  1. <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;" >  
  2.   <a class="navbar-brand" routerLink="">Routing Application</a>  
  3.   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  4.     <span class="navbar-toggler-icon"></span>  
  5.   </button>  
  6.   
  7.   <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  8.     <ul class="navbar-nav mr-auto">  
  9.         <!-- [routerLinkActiveOptions]="{ exact : true}" -->  
  10.       <li class="nav-item"  routerLinkActive="active" >  
  11.         <a class="nav-link" routerLink="/home">Home </a>  
  12.       </li>  
  13.       <li class="nav-item"  routerLinkActive="active" >  
  14.         <a class="nav-link" routerLink="/products">Products</a>  
  15.       </li>  
  16.       <li class="nav-item"  routerLinkActive="active">  
  17.           <a class="nav-link" [routerLink]="['/addproduct',0]">Add Product</a>  
  18.       </li>  
  19.   
  20.     </ul>  
  21.   
  22.       <button routerLink="/login" *ngIf="!isLoggedIn" class="btn btn-outline-success my-2 my-sm-0">Login</button>  
  23.       <button *ngIf="isLoggedIn" (click)="logOut()" class="btn btn-outline-success my-2 my-sm-0">Logout</button>  
  24.   </div>  
  25. </nav>  

Header.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { UserAuthService } from './Users/user-auth.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-header',  
  6.   templateUrl: './header.component.html',  
  7.   styleUrls: ['./header.component.css']  
  8. })  
  9. export class HeaderComponent implements OnInit {  
  10.   
  11.   constructor(private _userauth:UserAuthService) { }  
  12.   get isLoggedIn():boolean{  
  13.     return this._userauth.isLoggedIn;  
  14.   }  
  15.   logOut(){  
  16.     this._userauth.logout();  
  17.   }  
  18.   ngOnInit() {  
  19.   }  
  20. }  

Here, I have created isLoggedIn which will return true or false based on user’s logged in status, and I am using isLoggedIn property on my template to display either Login button or Logout button based on the value returned by isLoggedIn.

All About Routing In Angular Application
 

How to Guard Routes? (canActivate, canLoad)

It is always required that not every user has access to all the routes; say for example we don’t want to allow any user to have access to products pages like products list page and add new products page without logging In. We can do it simply by creating a guard for that.

Now to achieve the above-said use case, first I have created user-guard service as shown below,

  1. import { Injectable } from '@angular/core';  
  2. import { CanActivate,CanLoad, Router,  
  3.    RouterStateSnapshot, ActivatedRouteSnapshot, Route } from '@angular/router';  
  4. import { UserAuthService } from './user-auth.service';  
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class UserGuardService implements CanActivate,CanLoad {  
  9.   
  10.   constructor(private _user_auth:UserAuthService,private _router:Router) { }  
  11.   canActivate(_next:ActivatedRouteSnapshot,_state:RouterStateSnapshot):boolean{  
  12.       return this.checkLoggedIn(_state.url);  
  13.   }  
  14.   canLoad(_route:Route):boolean{  
  15.     return this.checkLoggedIn(_route.path);  
  16.   }  
  17.   checkLoggedIn(url:string):boolean{  
  18.     if(this._user_auth.isLoggedIn){  
  19.         return true;  
  20.     }  
  21.     this._user_auth.redirectURL=url;  
  22.     this._router.navigate(['/login']);  
  23.     return false;  
  24.   }  
  25. }  

Here in the above service, I have implemented CanActivate, CanLoad interface from angular/router package which will be used to protect our routes. Here we are checking the user’s logged-in status and based on that we are allowing the user to navigate to a particular page.

Also, update app.routing.ts file as shown below,

  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './home/home.component';  
  3. import { LoginComponent } from './Users/login/login.component';  
  4. import { ProductListComponent } from './Products/product-list/product-list.component';  
  5. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  6. import { PageNotFoundComponent } from './page-not-found/page-not-found.component';  
  7. import { UserGuardService } from './Users/user-guard.service';  
  8.   
  9. const arr: Routes = [  
  10.  {path: '', redirectTo: '/home', pathMatch: 'full'},  
  11.  {path: 'home', component: HomeComponent},  
  12.  {path: 'login', component: LoginComponent},  
  13.  {path:'products', canActivate:[UserGuardService], component:  ProductListComponent },  
  14.  {path:'addproduct/:id', canActivate:[UserGuardService],component: ProductAddComponent },  
  15.  {path: '**', component:PageNotFoundComponent }  
  16. ];  
  17.   
  18.  export const routing = RouterModule.forRoot(arr);  

So as I said before the products list and add product pages should be displayed only after the user is loggedIn,that can be taken care of by canActivate directive, so now when user requests for a particular page it will first check the credentials in auth-guard services inside canActiviate interface and then user will be allowed to visit a particular page.

Child Routes?

We can also manage routes using children property on routing array, say for example if we want to organize all routes related to the products under one parent object, we can define children inside the parent object as shown below,

  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './home/home.component';  
  3. import { LoginComponent } from './Users/login/login.component';  
  4. import { ProductListComponent } from './Products/product-list/product-list.component';  
  5. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  6. import { PageNotFoundComponent } from './page-not-found/page-not-found.component';  
  7. import { UserGuardService } from './Users/user-guard.service';  
  8.   
  9. const arr: Routes = [  
  10.   {path: '', redirectTo: '/home', pathMatch: 'full'},  
  11.   {path: 'home', component: HomeComponent},  
  12.   {path: 'login', component: LoginComponent},  
  13.   {path:'products',canActivate:[UserGuardService],  
  14.   children:[  
  15.   {path:'',component:ProductListComponent},  
  16.   {path:':id',component:ProductAddComponent},  
  17.   {path:':id/edit',component:ProductAddComponent}  
  18. ]  
  19. },  
  20.  {path: '**', component:PageNotFoundComponent }  
  21.  ];  
  22.   
  23.  export const routing = RouterModule.forRoot(arr);  

So, now if we request for http://localhost:4200/products/, it will first go to products object and then inside products object, it will go to its children which is an array of child component and then check for matching the path to load the component. In our particular case, it will load the product list component.

Also, we need to update the header.component.html because we had changed routing array.

  1. <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;" >  
  2.   <a class="navbar-brand" routerLink="">Routing Application</a>  
  3.   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  4.     <span class="navbar-toggler-icon"></span>  
  5.   </button>  
  6.   
  7.   <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  8.     <ul class="navbar-nav mr-auto">  
  9.         <!-- [routerLinkActiveOptions]="{ exact : true}" -->  
  10.       <li class="nav-item" [routerLinkActiveOptions]="{ exact : true}" routerLinkActive="active" >  
  11.         <a class="nav-link" routerLink="/home">Home </a>  
  12.       </li>  
  13.       <li class="nav-item" [routerLinkActiveOptions]="{ exact : true}" routerLinkActive="active" >  
  14.         <a class="nav-link" routerLink="/products">Products</a>  
  15.       </li>  
  16.       <li class="nav-item" [routerLinkActiveOptions]="{ exact : true}" routerLinkActive="active">  
  17.           <a class="nav-link" [routerLink]="['/products',0]">Add Product</a>  
  18.       </li>  
  19.   
  20.     </ul>  
  21.   
  22.       <button routerLink="/login" *ngIf="!isLoggedIn"  
  23.       class="btn btn-outline-success my-2 my-sm-0">Login</button>  
  24.       <button *ngIf="isLoggedIn" (click)="logOut()"  
  25.       class="btn btn-outline-success my-2 my-sm-0">Logout</button>  
  26.   </div>  
  27. </nav>  
All About Routing In Angular Application 

Now although I had requested for add product page, it will first redirect me to log in because of the user-guard service.

All About Routing In Angular Application 

Now after a successful login by default, it should redirect me to the product list page, but in this case, it will redirect me to add product page because of the redirecURL property of user-auth service.

All About Routing In Angular Application 

How to display spinner using routing event? (Resolver)

Well, we can display spinner in the angular application in various ways, but I am talking about displaying spinner using routing event. It will solve your two problems -- one it will prevent loading the page partially and other it will also display a spinner.

How many time have you faced a problem, when you navigate to a page and you are making an HTTP call to fetch the data, and your template/ HTML is loaded and still you are waiting to load your HTTP data; i.e. because of partial page loading, Angular manages to route locally so your HTML/template will be loaded, but still, you are waiting for HTTP calls to complete to display the data. As a solution to this, we can use one of the routing events, which will only load the page/navigate to page after your HTTP call completes, this way you can prevent to partial page loading and also able to display spinner.

Okay so first create product-resolver.service.ts, as shown below,

  1. import { Injectable } from '@angular/core';  
  2. import { Resolve,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';  
  3. import { Product, productResolved } from './product';  
  4. import { Observable, of } from 'rxjs';  
  5. import { ProductService } from './product.service';  
  6. import { map, catchError } from 'rxjs/operators';  
  7. @Injectable({  
  8.   providedIn: 'root'  
  9. })  
  10. export class ProductResolverService implements Resolve<productResolved> {  
  11.   constructor(private productdata:ProductService) { }  resolve(next:ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<productResolved>  
  12.   {  
  13.       return this.productdata.getAllProducts().pipe(  
  14.         map(product => ({ product: product,errorMessage:'' })),  
  15.         catchError(err=>{  
  16.           console.log(err);  
  17.           return of({ product: null,errorMessage:err.message });  
  18.         })  
  19.       );  
  20.     }  
  21. }  

Here, I had implemented the Resolve method of the interface, which will return the productResolved Observable before navigating or loading the page. Below are the product and product resolved classes,

  1. export class Product{  
  2.   constructor(public pimg:string,public pname:string,  
  3.     public pprice:number,public soh:number){}  
  4. }  
  5. export class productResolved{  
  6.   constructor(public product:any[],public errorMessage:string){}  
  7. }  

Here, Product class will describe what type of data we are receiving from HTTP call, and productResolved class is for holding the product data as well as errors if any.

Now in order to make Resolver work we need to do some adjustment in app.routing.ts as shown below,

All About Routing In Angular Application 
  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './home/home.component';  
  3. import { LoginComponent } from './Users/login/login.component';  
  4. import { ProductListComponent } from './Products/product-list/product-list.component';  
  5. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  6. import { PageNotFoundComponent } from './page-not-found/page-not-found.component';  
  7. import { UserGuardService } from './Users/user-guard.service';  
  8. import { ProductResolverService } from './Products/product-resolver.service';  
  9.   
  10. const arr: Routes = [  
  11.   {path: '', redirectTo: '/home', pathMatch: 'full'},  
  12.  {path: 'home', component: HomeComponent},  
  13.  {path: 'login', component: LoginComponent},  
  14.  {path:'products',resolve:{productData:ProductResolverService},  
  15.  canActivate:[UserGuardService],  
  16. children:[  
  17.   {path:'',component:ProductListComponent},  
  18.   {path:':id',component:ProductAddComponent},  
  19.   {path:':id/edit',component:ProductAddComponent}  
  20. ]  
  21. },  
  22.  {path: '**', component:PageNotFoundComponent }  
  23.  ];  
  24.   
  25.  export const routing = RouterModule.forRoot(arr);  

Now to display the spinner, we need to subscribe to the routing events on root component; i.e. app.component.html, by subscribing to root component. We don’t need to put the spinner on each and every page, we just need to put the spinner on root component only, below is how app.component.ts will look:

  1. import { Component } from "@angular/core";  
  2. import { Router,Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from "@angular/router";  
  3.   
  4. @Component({  
  5.   selector: "app-root",  
  6.   templateUrl: "./app.component.html",  
  7.   styleUrls: ["./app.component.css"]  
  8. })  
  9. export class AppComponent {  
  10.   title = "angularRoutingApplication";  
  11.   loading = true;  
  12.   
  13.   constructor(private _router:Router){  
  14.     _router.events.subscribe((routerEvent: Event) => {  
  15.       this.checkRouterEvent(routerEvent);  
  16.     });  
  17.   }  
  18.   
  19.   checkRouterEvent(routerEvent: Event): void {  
  20.     if (routerEvent instanceof NavigationStart) {  
  21.       this.loading = true;  
  22.       console.log('router event start');  
  23.     }  
  24.   
  25.     if (routerEvent instanceof NavigationEnd ||  
  26.         routerEvent instanceof NavigationCancel ||  
  27.         routerEvent instanceof NavigationError) {  
  28.           console.log('router event finish');  
  29.       this.loading = false;  
  30.     }  
  31.   }  
  32. }  

Here I am subscribing to routing events first and then checking for navigationStart and NavigationEnd, based on that I am updating the loading property to true or false, which will be used on HTML/template to display the spinner. Below is a snippet of app.component.html,

  1. <div  *ngIf="loading"  class="spinner-border text-primary" role="status">  
  2.   <span class="sr-only">Loading...</span>  
  3. </div>  
  4. <div *ngIf="loading" class="spinner-border text-secondary" role="status">  
  5.   <span class="sr-only">Loading...</span>  
  6. </div>  
  7. <div *ngIf="loading" class="spinner-border text-success" role="status">  
  8.   <span class="sr-only">Loading...</span>  
  9. </div>  
  10. <div *ngIf="loading" class="spinner-border text-danger" role="status">  
  11.   <span class="sr-only">Loading...</span>  
  12. </div>  
  13. <div *ngIf="loading" class="spinner-border text-warning" role="status">  
  14.   <span class="sr-only">Loading...</span>  
  15. </div>  
  16. <div *ngIf="loading" class="spinner-border text-info" role="status">  
  17.   <span class="sr-only">Loading...</span>  
  18. </div>  
  19. <div *ngIf="loading" class="spinner-border text-light" role="status">  
  20.   <span class="sr-only">Loading...</span>  
  21. </div>  
  22. <div *ngIf="loading" class="spinner-border text-dark" role="status">  
  23.   <span class="sr-only">Loading...</span>  
  24. </div>  
  25. <app-header></app-header>  
  26. <router-outlet></router-outlet>  

So, now when I request, http://localhost:4200/products first it will navigate us to the login page. Remember we had used user-guard service, then after login, it will first call resolver service to fetch the data, and then only it will navigate to the product list page. Below is the code snippet of product-list.component.ts,

  1. import { Component, OnInit } from '@angular/core';  
  2. import { Observable } from 'rxjs';  
  3. import { Product, productResolved } from '../product';  
  4. import {  ActivatedRoute } from '@angular/router';  
  5. @Component({  
  6.   selector: 'app-product-list',  
  7.   templateUrl: './product-list.component.html',  
  8.   styleUrls: ['./product-list.component.css']  
  9. })  
  10. export class ProductListComponent implements OnInit {  
  11. items:Product[]=[];  
  12. errorMessage:string='';  
  13. data:productResolved;  
  14.   constructor(private _router:ActivatedRoute) {  
  15.   this.data=this._router.snapshot.data["productData"];  
  16.   }  
  17.   ngOnInit() {  
  18.     this.items=this.data.product;  
  19.     this.errorMessage=this.data.errorMessage;  
  20.   }  
  21. }  

So, now on product list.component.ts, instead of making an HTTP call, we will just use the data which has already been fetched by resolver services:

  1. this.data=this._router.snapshot.data["productData"];  

Here “prodcutData” is the same name which we had used while declaring the app.routing.ts,

All About Routing In Angular Application
 
All About Routing In Angular Application 

After routes gets resolved it will display the product list page.

All About Routing In Angular Application
 

How to make routing case insensitive?

The routes in the Angular application are case sensitive, i.e. if you have defined

{path: 'home', component: HomeComponent},

And if you request http://localhost:4200/home, it will work fine, but it will not work with following routes,

  • http://localhost:4200/Home
  • http://localhost:4200/HOME
  • http://localhost:4200/hoME, etc

so to make all above URL work in Angular applications, I found a common workaround,  UrlSerializer.

We can create lowecaseurlserializer which is derived from defaulturlserializer as shown below,

  1. import { DefaultUrlSerializer, UrlTree } from '@angular/router';  
  2. export class LowerCaseUrlSerializer extends DefaultUrlSerializer {  
  3.     parse(url: string): UrlTree {  
  4.       return super.parse(url.toLowerCase());  
  5.     }  
  6. }  

Which will simply convert all URLs to lowercase so that it will match our routing array. Now in order to make this lowecaseurlserializer to work we need to make an adjustment to app.module.ts as shown below,

All About Routing In Angular Application 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5. import { routing } from './app.routing';  
  6. import { environment } from '../environments/environment';  
  7. import { HttpClientModule } from '@angular/common/http';  
  8. import { ProductAddComponent } from './Products/product-add/product-add.component';  
  9. import { LoginComponent } from './Users/login/login.component';  
  10. import { HomeComponent } from './home/home.component';  
  11. import { HeaderComponent } from './header.component';  
  12. import { ProductListComponent } from './Products/product-list/product-list.component';  
  13. import { PageNotFoundComponent } from './page-not-found/page-not-found.component';  
  14. import { UrlSerializer } from '@angular/router';  
  15. import { LowerCaseUrlSerializer } from './lowerCaseUrlSerializer';  
  16. @NgModule({  
  17.   declarations: [  
  18.     AppComponent,  
  19.     ProductAddComponent,  
  20.     LoginComponent,  
  21.     HomeComponent,  
  22.     HeaderComponent,  
  23.     ProductListComponent,  
  24.     PageNotFoundComponent  
  25.   ],  
  26.   imports: [  
  27.     BrowserModule,  
  28.     FormsModule,  
  29.     routing,  
  30.     HttpClientModule      
  31.   ],  
  32.   providers: [  
  33.     {  
  34.       provide:UrlSerializer,  
  35.       useClass:LowerCaseUrlSerializer  
  36.     }  
  37.   ],  
  38.   bootstrap: [AppComponent]  
  39. })  
  40. export class AppModule { }  

Download

Script for products table:

  1. CREATE TABLE IF NOT EXISTS `products` (  
  2.   `p_id` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `pname` varchar(50) NOT NULL,  
  4.   `pprice` int(11) NOT NULL,  
  5.   `pimg` varchar(200) NOT NULL,  
  6.   `soh` int(11) NOT NULL,  
  7.   PRIMARY KEY (`p_id`)  
  8. ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;