簡體   English   中英

Angular 2:如何從 CanLoad 實現中獲取路由參數?

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

我已經向延遲加載的狀態添加了一個canLoad保護。 我遇到的問題是,如果使用 router.navigate() 從不同狀態初始化狀態,我將無法獲得任何路由參數。

所以這是我的路由配置:

path: 'programs/:programId/dashboard',
loadChildren: './program.module#ProgramModule',
canLoad: [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);
    }
  }
}

我嘗試注入 ActivatedRoute 以嘗試從那里獲取它們以從那里獲取它,但什么也沒有。

如果用戶在瀏覽器中輸入 URL,則沒有問題,因為我可以從 location 對象中提取參數。 但是在使用 route.navigate 時,瀏覽器的位置仍然設置為之前的狀態。

任何幫助或想法將不勝感激。

我嘗試做類似的事情,最終改為使用 canActivate 守衛。 另請注意,canLoad 防護會阻止您可能想要執行的任何預加載。

從理論上講,如果用戶無法訪問路線,甚至不加載它也很好。 但它的實踐似乎太有限,無法做出決定。

你可以嘗試的東西(我之前嘗試這樣做時沒有想到)......你可以添加一個父路由(無組件),它有一個可以檢查參數的 canActivate 保護。 如果用戶有授權,則路由到延遲加載的路由。

我能夠使用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;
}

您只需要在構造函數中注入 Location 對象。

為什么不從段的路徑構建 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)
}

首先你可以聲明變量如下:

routeSnapshot: ActivatedRouteSnapshot;

然后在構造函數中調用 ActivatedRouteSnapshot 類如下:

constructor(private routeSnapshot: ActivatedRouteSnapshot)

現在你可以使用 this.routeSnapshot 到 canLoad 方法中

我知道為時已晚,但我找到了像魅力一樣工作的解決方案。 我希望這能幫助像我一樣面臨同樣問題的新成員

  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