When a user is logged out in Angular 2 router and they try to navigate to a page that requires them to be logged in, I need the app.ts file to redirect them.
I am utilizing typescript along with angular 2.
Oddly enough, the redirection works for certain pages. However, when there is code in the constructor, it triggers. My goal is to immediately redirect the user to the homepage if they are not logged in.
In the app.ts file, I check if the user is logged in and initiate this code if they are not:
this.router.navigate(['Home']);
While this method works for basic pages, accessing more complex pages like the search page generates console errors as it accesses the component's constructor.
This is the route configuration in the app.ts file:
@RouteConfig([
{ path: '/', component: Home, as: 'Home'},
{ path: '/home', component: Home, as: 'Home' },
{ path: '/login', component: Login, as: 'Login' },
{ path: '/register/:id', component: Register, as: 'Register' },
{ path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' },
{ path: '/dashboard', component: Dashboard, as: 'Dashboard' },
{ path: '/search', component: SearchJobs, as: 'Search' },
{path:'/**', redirectTo: ['Home']}
])