Angular2 路由器 - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录的情况下重定向到主页 [英] Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in

查看:19
本文介绍了Angular2 路由器 - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录的情况下重定向到主页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular2 路由器 - 任何人都知道如何在 app.ts 中使用 canActivate,以便我可以在未登录的情况下重定向到主页

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

我正在使用 typescript 和 angular 2.

I'm using typescript and angular 2.

当前在我的 app.ts 文件中的构造函数下的尝试:

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

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

它目前没有被击中.知道为什么吗?

It currently doesnt get hit. Any idea why?

推荐答案

所以文档看起来是这样的.

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

在 Angular2 文档的底部,他们添加了这个片段:从 angular2/router 导出https://angular.io/docs/ts/latest/api/router/CanActivate-装饰器.html

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

因此,如果您希望从更高级别进行重定向.您不会使用 CanActivate 装饰器,而是会执行以下操作.

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.
  }
}

此实现处理对指令的任何新请求,并在您的路由身份验证逻辑所在的位置运行 activate 函数.上面的代码将被称为 AuthRouterOutlet 之类的东西.并且您必须通过

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]

这篇关于Angular2 路由器 - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录的情况下重定向到主页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆