If you want to implement a guard in your app routing module that displays content based on the user's country, you can follow these steps:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule, PreloadAllModules, NoPreloading } from '@angular/router';
import { MainComponent } from './main/main.component';
import { CountryGuard } from './auth/services/country.guard';
const gbRoutes: Routes = [{
path: 'gb',
loadChildren: () => import('./Sale_en_GB/Sale_en_GB.module').then(mod => mod.SalesGBModule),
canLoad: [CountryGuard],
}];
const frRoutes: Routes = [{
path: 'fr',
loadChildren: () => import('./Sale_fr_FR/Sale_fr_FR.module').then(mod => mod.SalesFRModule),
canLoad: [CountryGuard],
}];
const routes: Routes = [
{
path: '',
redirectTo: 'gb', //default
pathMatch: 'full'
},
{
path: '',
component: MainComponent, //there will be a main component for both modules.
canActivate: [CountryGuard],
children: [
...gbRoutes,
...frRoutes,
]
},
]
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})
export class AppRoutingModule { }
country.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild, CanLoad, Route, UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Resolve } from '@angular/router';
import { Observable, throwError, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CountryGuard implements CanActivate, CanActivateChild, CanLoad, Resolve<any> {
token: any;
user: any;
constructor(private router: Router) {}
canActivate(){
if (checkCountry('GB')) { // implement logic to check user country here
this.router.navigate(['/gb']);
} else if(checkCountry('FR')) {
this.router.navigate(['/fr']);
}
return false;
}
canActivateChild(){
return true;
}
canLoad(){
if (checkCountry('GB')) { // implement logic to check user country here
this.router.navigate(['/gb']);
} else if(checkCountry('FR')) {
this.router.navigate(['/fr']);
}
return false;
}
}