简体   繁体   English

Angular 2:如何从 CanLoad 实现中获取路由参数?

[英]Angular 2: how do I get route parameters from CanLoad implementation?

I've added a canLoad guard to a state that's lazy loaded.我已经向延迟加载的状态添加了一个canLoad保护。 The problem that I'm having is that I can't get any route parameters if the state is being initialized from a different state using router.navigate().我遇到的问题是,如果使用 router.navigate() 从不同状态初始化状态,我将无法获得任何路由参数。

So here is my route configuration:所以这是我的路由配置:

path: 'programs/:programId/dashboard',
loadChildren: './program.module#ProgramModule',
canLoad: [ProgramGuard]

and this is the short version of ProgramGuard:这是 ProgramGuard 的简短版本:

export class ProgramGuard implements CanLoad {

  canLoad(route: Route): Observable<boolean> {

    //route object doesn't have any reference to the route params

    let programId = paramFromRoute;

    return Observable.create(observer => {

       if (programId == authorizedProgramId)
        observer.complete(true);
       else
        observer.complete(false);
    }
  }
}

I have tried injecting ActivatedRoute to try to get them from there to get it from there, but nothing.我尝试注入 ActivatedRoute 以尝试从那里获取它们以从那里获取它,但什么也没有。

If the user types the URL in the browser, then there is no problem because I can extract the parameters from the location object.如果用户在浏览器中输入 URL,则没有问题,因为我可以从 location 对象中提取参数。 But when using route.navigate, the browser's location is still set to the previous state.但是在使用 route.navigate 时,浏览器的位置仍然设置为之前的状态。

Any help or ideas will be greatly appreciated.任何帮助或想法将不胜感激。

I tried to do something similar and ended up changing to a canActivate guard instead.我尝试做类似的事情,最终改为使用 canActivate 守卫。 Note also that the canLoad guards block any preloading that you may want to do.另请注意,canLoad 防护会阻止您可能想要执行的任何预加载。

In theory, if a user could not access a route, it would be great to not even load it.从理论上讲,如果用户无法访问路线,甚至不加载它也很好。 But it practice it seems to be too limited to allow making a determination.但它的实践似乎太有限,无法做出决定。

Something you could try (I didn't think of it earlier when I was trying to do this) ... you could add a parent route (component-less) that has a canActivate guard that can check the parameters.你可以尝试的东西(我之前尝试这样做时没有想到)......你可以添加一个父路由(无组件),它有一个可以检查参数的 canActivate 保护。 Then route to the lazy loaded route if the user has authorization.如果用户有授权,则路由到延迟加载的路由。

I was able to retrieve the path including the route parameters using The Location object.我能够使用Location对象检索包含路由参数的路径。

canLoad() {
   //dont even load the module if not logged in
   if (!this.userSessionService.isSessionValid()) {
     this.userSessionService.redirectUrl = this.location.path();
     this.router.navigate(['/auth']);
     return false;
   }
   return true;
}

You just need to inject the Location object in the constructor.您只需要在构造函数中注入 Location 对象。

Why not building the url from the paths of the segments?为什么不从段的路径构建 url?

/**
 * Test if the user as enough rights to load the module
 */
canLoad(route: Route, segments: UrlSegment[]): boolean | Observable<boolean> | Promise<boolean> {
    // We build the url with every path of the segments
    const url = segments.map(s => s.path).join('/')

    // We handle the navigation here 
    return this.handleNavigation(url, route)
}

first you can declare variable Like the following :首先你可以声明变量如下:

routeSnapshot: ActivatedRouteSnapshot;

then in constructor call ActivatedRouteSnapshot class Like the following :然后在构造函数中调用 ActivatedRouteSnapshot 类如下:

constructor(private routeSnapshot: ActivatedRouteSnapshot)

now you can use this.routeSnapshot into canLoad method现在你可以使用 this.routeSnapshot 到 canLoad 方法中

I know its too late, but I found the solution that work like charm.我知道为时已晚,但我找到了像魅力一样工作的解决方案。 I hope this will help new members who face the same problem like me我希望这能帮助像我一样面临同样问题的新成员

  canLoad(
    route: Route,
    segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
    if (!this.auth.isLoggedIn()) {
      this.route.navigate(['auth/login'], { queryParams: { redirect_url: '/' + segments[0].path } });
      return false;
    }
    return true;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM