1

I am developing a single page app using AngularJS2, I want to redirect to login page if user is not login, how can I check condition for each route to check for login?

import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { SalesComponent } from './sales/sales.component';
import { LogoutComponent } from './logout/logout.component';

const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'employees', component: EmployeeComponent },
  { path: '404-not-found', component: NotFoundComponent },
  { path: 'logout', component : LogoutComponent },
  { path: '**', redirectTo: '/404-not-found' }
];

export const routing = RouterModule.forRoot(appRoutes);

I want to check for login status in app.routing.ts file, and if I am not login I should redirect to login. Thanks for help.

aditya
  • 149
  • 1
  • 3
  • 15

2 Answers2

0

Please refer to the answers at Angular2 redirect to login page

The solution using CanActivate interface implementation is a robust solution with the current release of the new Router.

Community
  • 1
  • 1
Amarjeet Singh
  • 121
  • 1
  • 2
0

You have to create auth service and auth guard service as explained on Routing and Navigation document and need to configure it in route config.

ranakrunal9
  • 13,320
  • 3
  • 42
  • 43