Angular2路由器 - 任何人都知道如何使用canActivate在app.ts这样,如果没有登录,我可以重定向到主页 [英] Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in

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

问题描述

Angular2路由器 - 任何人都知道如何使用canActivate在app.ts这样,如果没有登录,我可以重定向到首页

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

我使用的打字稿及角2。

I'm using typescript and angular 2.

在我app.ts文件我的构造在当前的尝试:

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?

推荐答案

,以便文档看起来这是它的出口。

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 /路由器出口
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.
  }
}

此实现处理一个指令的任何新的请求,并运行激活功能,在您的路由认证逻辑会。
上面的code将被称为像AuthRouterOutlet。
你将不得不通过将其添加到您的app.ts

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路由器 - 任何人都知道如何使用canActivate在app.ts这样,如果没有登录,我可以重定向到主页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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