typescript - Angular2 Router - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录时重定向到主页

标签 typescript angular angular2-routing

Angular2 Router - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录时重定向到主页

我正在使用 typescript 和 angular 2。

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

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

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

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

最佳答案

所以文档看起来像它导出的内容。

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-decorator.html

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

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

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

将其添加到您的 app.ts
directives: [ AuthRouterOutlet]

关于typescript - Angular2 Router - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录时重定向到主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34754295/

相关文章:

typescript - Phaser + TypeScript 严格模式

angular - 如何为输入字段提供 2 路格式化程序?

javascript - 无法绑定(bind)到 'routerLink',因为它不是已知的 native 属性

javascript - Angular 5 : HTTP post `Response for preflight has invalid HTTP status code 400.`

javascript - 在 Node.js 中使用 TypeScript

html - 模型更改后 Angular 2 不更新 View

angular - 版本中的错误 'EMFILE: too many open files, open' VSTS

angular - 如何使用 :id parameter in Angular2 创建子路由

Angular 重定向到默认 subview

javascript - Angular 6 - 路由未发生 - Mat-table 行