2017-06-13 60 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]);