如何在ng2 Guard canActivate中获取目标路由? [英] How to get target route in ng2 guard canActivate?

查看:131
本文介绍了如何在ng2 Guard canActivate中获取目标路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取用户试图在角度2的canActivate防护中打开的路线?

How can I get the route which the user is trying to open within an canActivate guard in angular 2?

我如何使监视每个路由参数的变化,例如.更改路线内的ID?

How can I make the guard watch for every route parameter change eg. a change of the id within the route?

import { Injectable }       from '@angular/core';
import {Observable, Observer, Subject} from "rxjs/Rx";

@Injectable()
export class RightsGuard implements CanActivate {
    constructor(
      private router: Router,
      private route: ActivatedRoute
      // private state: RouterStateSnapshot
    ) { }

    canActivate(): Observable<boolean> | boolean {
      var targetUrl = ???
      // var targetUrl = this.router.url // is showing previous url?
      return true;
    }
}

Angular 2使用以下方法获得建议的答案 private state: RouterStateSnapshot 然后this.route.url对我不起作用,因为它会引发DI错误:

Suggested answer in Angular 2 get current route in guard using private state: RouterStateSnapshot and then this.route.url does not work for me, since it throws an DI error:

Error: Uncaught (in promise): Error: DI Error
Error: DI Error

推荐答案

以下内容似乎有效,但是不能在构造函数中注入路由和状态,因为这会导致错误.

The following seems to work, however route and state must not be injected in the constructor since this causes errors.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
  console.log("route-access",state);
}

但是,这会导致每个路由只调用一次警卫的问题.对于诸如:id之类的路由参数的更改,不会调用防护.但这似乎与3.2路由器中的错误相关:

However this results in the problem that the guard is only called once for each route. For changes of route parameters like :id the guard is not being invoked. But this seems to correlate with a bug in the 3.2 router:

  • Calling angular2 route guard multiple times
  • https://github.com/angular/angular/issues/12851

这篇关于如何在ng2 Guard canActivate中获取目标路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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