0

Angular 2 router - When logged out and a user tries to navigate to a logged in page I need the app.ts to redirect.

I'm using typescript with angular 2.

For some reason the redirect works for some pages. But when I have code in the constructor it hits it. I want to redirect the user to homepage straight away if not logged in.

I'm checking if they are logged in and then I do this code if they are not logged in in the app.ts file:

       this.router.navigate(['Home']);

This works for basic pages but when I try access my search page for example I get console errors because its accessing the components constructor.

This is my route config 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']}
 ])
Sasxa
  • 40,334
  • 16
  • 88
  • 102
AngularM
  • 15,982
  • 28
  • 94
  • 169
  • Check these two options: https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html & https://angular.io/docs/ts/latest/api/router/OnActivate-interface.html – Langley Jan 12 '16 at 21:03
  • I'm not sure how to get those working - the documentation is poor on those websites – AngularM Jan 12 '16 at 21:25
  • Add the `@CanActivate` annotation to your component and the function you pass to it will get called before the constructor of your component. – Langley Jan 12 '16 at 21:28
  • I've just tried this in my app.ts under my constructor: CanActivate() { console.log('here'); } But its not getting hit at all – AngularM Jan 12 '16 at 21:32
  • CanAtivate is an Anotation, not a function, you pass a function to it, like in the example: `@CanActivate( () => console.log('here') ) export class YourComponent {` – Langley Jan 12 '16 at 21:52
  • Ok, I've put this in the app.ts file: @CanActivate( () => console.log('here') ) But I get loads of typescript errors. – AngularM Jan 12 '16 at 21:55
  • like which one? Did you import the CanActivate annotation ? – Langley Jan 12 '16 at 21:56

3 Answers3

0

Well you already posted something on this topic but i'll answer it here in case this is something others look at more. You can redirect a user by utilizing the @CanActivate decorator. What this does is that it will run before the component initialization. if the function returns true the component will load else it will redirect. I assume it will go to the route you set useAsDefault :true;

export CanActivate(options : CanActivateAnnotation) : (hook: (next: ComponentInstruction, prev: ComponentInstruction) =>
                     Promise<boolean>| boolean) => ClassDecorator

@CanActivate((next, prev) => {
      // This must prove to be true for the component @ this route to load
      if(next.urlPath != '/Login'){ 
         return Promise.resolve(this._authService.getIsAuth() 
         && localStorage.getItem('authToken')
      }
      /*
       If CanActivate returns or resolves to false, the navigation is 
       cancelled. If CanActivate throws or rejects, the navigation is also
       cancelled. If CanActivate returns or resolves to true, navigation 
       continues, the component is instantiated, and the OnActivate hook of 
       that component is called if implemented.
      */
   }
);
inoabrian
  • 3,762
  • 1
  • 19
  • 27
  • where do I put this code? in my app.ts file? if so where abouts ? (inside the component?) – AngularM Jan 26 '16 at 15:13
  • This piece goes before each component. If you look at my answer here : http://stackoverflow.com/questions/34754295/angular2-router-anyone-know-how-to-use-canactivate-in-app-ts-so-that-i-can-red/34759270?noredirect=1#comment57283408_34759270. It will show you how to do it at the app.ts level by overriding the router-outlet. – inoabrian Jan 26 '16 at 15:15
  • I have loads of components though. I want something like angular 1.x interceptor. – AngularM Jan 26 '16 at 15:33
  • then use this answer http://stackoverflow.com/questions/34754295/angular2-router-anyone-know-how-to-use-canactivate-in-app-ts-so-that-i-can-red/34759270?noredirect=1#comment57283408_34759270 – inoabrian Jan 26 '16 at 15:37
0

You need to write below code into app.ts as you are asking.

import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';

export class AppComponent  {
    constructor(router:Router){
       this.router=router;
       this.router.subscribe((nextValue) => {
       console.log(nextValue)
       if (nextValue !== 'login' && !autheService.isAuthenticated) {
                      this.router.navigate(['/Login']);
       }
}

have a look here plnkr

If you consider angular1. We have,

$scope.$on('$routeChangeStart', function(next, current) { 
   ... you could trigger something here ...
 });

and other events if route fails and so on to deal with routing using ui.router. So you can replace Angular1 with this above mentioned code.

I think what you are asking for, can be achieved by this with minimum efforts. Still @canActive other points are valid.

I hope this will help.

micronyks
  • 54,797
  • 15
  • 112
  • 146
  • The above code only works when changing url and not on refresh. When I refresh it still reaches the component and doesn't redirect them to my home page view – AngularM Jan 13 '16 at 08:29
0

If you are on RC4 version, check CanActivate interface

You will need to create a class which implements CanActivate interface and protect your routes using canActivate property of RouterConfig

Check the latest router documentation for examples.

Ajay Ambre
  • 89
  • 6