2017-06-13 58 views
0

我一直在構建一個Angular 2應用程序,它的設置使得如果我將用戶導航到另一個路線的登錄路線作爲第二個參數,用戶將被重定向到該路線之後登錄。Angular 2如何訪問當前路徑路徑

因此,例如,用戶嘗試導航到路線/客戶,但他們的登錄已過期。我使用警衛將他們重定向到/ login/customer,他們登錄然後重定向回到/ customer。這對我的衛兵很有效,但試圖在我的組件中使用它會導致問題。

問題是,我的組件內我似乎無法獲得當前路徑。

我已經嘗試了幾件事情,都使用ActivatedRoute並且都返回一個空字符串。

場景:用戶在/客戶路線上並點擊添加新客戶。該API返回一個錯誤,說明請求是由過期的令牌產生的。然後我需要按上面所述調用router.navigate,這意味着我需要確定當前路線(/客戶)以將其包含在導航中。

constructor(
    private activatedRoute: ActivatedRoute, 
    private authService: AuthService, 
    private router: Router; 
) { } 

private addCustomer(customer): void { 
    return this.authService.post(API.CUSTOMER, customer) 
    .mergeMap(...) 
    .catch(error => { 
     this.router.navigate(['/login', this.activatedRoute.snapshot.url[0].path]); // This is very simple and I like it but url is always an empty array. 
     return this.activatedRoute.url 
     .map(segments => { 
      this.router.navigate(['/login', segments.join('')]); // I just get and empty string from this. 
     }); 
    }); 
} 
+0

檢查此答案https://stackoverflow.com/a/44486971/2545680 –

回答

0

我能夠使用香草JavaScript來實現這一更容易。

this.router.navigate(['/login', window.location.pathname]);