Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

typescript - Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in

Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in

I'm using typescript and angular 2.

Current attempt under my constructor in my app.ts file:

   canActivate(instruction) {           
               console.log("here - canActivate");
               console.log(instruction);

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

It currently doesnt get hit. Any idea why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So the documentation looks like this is what it exports.

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.
      */
   }
);

At the bottom of the Angular2 documentation they add this snippet : exported from angular2/router https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html

So if you are looking to do redirection from a higher level. You would not use the CanActivate decorator you would do the following.

import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';
import {Login} from '../login/login';
import {UserService} from '../../Services/userService'; // a service to handle auth

@Directive({
  selector: 'router-outlet'
})
export class AuthRouterOutlet extends RouterOutlet {
  publicRoutes: any;
  private parentRouter: Router;

  constructor(private _userService:UserService, _elementRef: ElementRef, _loader: DynamicComponentLoader,
              _parentRouter: Router, @Attribute('name') nameAttr: string) {
    super(_elementRef, _loader, _parentRouter, nameAttr);

    this.parentRouter = _parentRouter;
    this.publicRoutes = {
      '/login': true,
      '/signup': true
    };
    // publicRoutes will be the routes auth is not needed for.
  }

  activate(instruction: ComponentInstruction) {
    var url = this.parentRouter.lastNavigationAttempt;
    if (!this.publicRoutes[url] && this._userService.getAuth()) {
      // todo: redirect to Login, may be there a better way?
      this.parentRouter.navigateByUrl('/login');
    }
    return super.activate(instruction);
    // we return super.activate(instruction) here so the router can activate the requested route and it's components.
  }
}

This implementation handles any new request to a directive and runs the activate function where your route authentication logic will be. The code above would be called something like AuthRouterOutlet. and you would have to add it to your app.ts via the

directives: [ AuthRouterOutlet]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...