I've setup a simple routing for my angular 4 app that consists of a sidemenu created using Tetradata Covalent and Angular Material i'm using this Angular 2/4 Authentication tutorial to handle login, however all child router links are redirecting to the default page(dashboard). Any help or advice would be highly appreciated.
app.routing.ts
export const APP_ROUTES: Routes = [
{path: 'login', component: HomeComponent},
{ path: '', redirectTo: 'mainpage', pathMatch: 'full' },
{ path: '**', redirectTo: 'mainpage' },
{
path: 'mainpage',
component: MainPageComponent,
canActivate:[AuthGuard],
children: [
{path: 'order', component: OrderComponent},
{path: 'dashboard', component: DashboardComponent},
{path: 'stock', component: StockComponent},
{path: 'Report/sales', component: SalesComponent},
{path: '', redirectTo: 'dashboard', pathMatch: 'full'}
{path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
]
}
];
page.component.html
<td-layout>
<td-navigation-drawer flex sidenavTitle="EzyAgric" logo="assets:logo" name="Akorion" email="info.akorion.com">
<md-nav-list>
<a md-list-item [routerLink]="['dashboard']">
<md-icon>dashboard</md-icon>
Dashboard</a>
<md-divider></md-divider>
<h3 md-subheader>Orders</h3>
<a md-list-item [routerLink]="['stock']">
<md-icon>archive</md-icon>
Stock
</a>
<a md-list-item [routerLink]="['order']">
<md-icon>shopping_cart</md-icon>
Received Orders
</a>
</td-navigation-drawer>
<td-layout-nav [toolbarTitle]="getTitle()" >
<div class="example-scrolling-content">
<router-outlet></router-outlet>
</div>
</td-layout-nav>
</td-layout>
AuthGuard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
In your app.routing.ts where you define your routes move the wildcard line to the end after you have defined all your routes.
export const APP_ROUTES: Routes = [
{path: 'login', component: HomeComponent},
{ path: '', redirectTo: 'mainpage', pathMatch: 'full' },
{
path: 'mainpage',
component: MainPageComponent,
canActivate:[AuthGuard],
children: [
{path: 'order', component: OrderComponent},
{path: 'dashboard', component: DashboardComponent},
{path: 'stock', component: StockComponent},
{path: 'Report/sales', component: SalesComponent},
{path: '', redirectTo: 'dashboard', pathMatch: 'full'}
{path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
]
},
{ path: '**', redirectTo: 'mainpage' } // this needs to be after other routes
];
Since it is a wild card route angular will hit this route before hitting any other route since routes order matter.