How to Append Parameters Before Routing Globally in Ionic

In some cases, you might need to add parameters dynamically to your route globally in an Ionic application. This approach can be especially useful when dealing with authentication tokens, language preferences, or other persistent parameters.

This tutorial walks you through the steps to implement this functionality efficiently.

Example:

  • http://localhost/tenant-1/main
  • http://localhost/tenant-2/main

But we don’t want to change every single router. It will take time and hard for maintenance and scaling. So, I will show you how to modify the router globally in a single place.

Why Append Parameters to Routes?

Appending parameters globally allows you to:

  1. Maintain consistent state across all routes.
  2. Simplify parameter management by centralizing it.
  3. Reduce repetitive code in individual components.

Ok, Let’s go.

Step-by-Step Implementation

1. Use Angular’s Route Reuse Strategy

Ionic uses Angular’s Router under the hood, which makes it flexible to customize routing behaviors. By implementing a RouteReuseStrategy, you can append query parameters globally.

2. Modify the Router Behavior

Override the default routing behavior by introducing the RouterInjectService class:

// router.guard.ts
export const RouterGuard: CanActivateFn = (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean => {
    return inject(RouterInjectService).canActivate(next, state);
}

@Injectable({ providedIn: 'root' })
class RouterInjectService {
  constructor(private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const tenantName = 'tenantName'; // Get or fetch from a service
    if (!state.url.includes(`${tenantName}`)) {
        this.router.navigate([`/${tenantName}${state.url}`]);
        return true;
    }    
    return true;
  }
}

We have main router here to make sure. When user input http//localhost/main into address browser. It will trigger the RouterGuard to append the routing to ‘tenantName:/main’ router.

The second router ‘tenantName:/main’ to make sure the URL don’t facing the issue 404 not found.

// app-routing.module.ts
const routes: Routes = [
  {
    path: 'main',
    loadChildren: () => import('./ui-pages/main/main.module').then( m => m.MainPageModule),
    canActivate: [RouterGuard]
  },
  {
    path: 'tenantName:/main',
    loadChildren: () => import('./ui-pages/main/main.module').then( m => m.MainPageModule),
    canActivate: [RouterGuard]
  }
}

Conclusion

By appending parameters globally, you can enhance your app’s routing capabilities and maintain consistent state across your application. With this approach, you not only simplify the development process but also make your Ionic app more dynamic and user-friendly.

F G+ T

tuandph

Khởi đầu với .NET từ năm 2013 đến nay. Hiện tại mình đang làm full-stack developer. Yêu thích lập trình & chia sẽ kiến thức. Thời gian rảnh thường làm những tool vui vui và viết lách kể lệ sự đời.