2016-11-09 34 views
0

我有page1和page2。我在page2路線上添加了canActivate gaurd,想知道我是否來自page1?我怎麼做?Angular 2 - 如何從canactivate gaurd中的url導航

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    //If from Page 1 { clearCache() } 
    return true; 
    } 

在此先感謝。

回答

4

首先DOIT這樣的:如果你想用戶重定向到從他/她是從哪裏來的網址,你可以做這樣的

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
     console.log(state.url); 
} 

:它會給你一個網址的信息,請閱讀official tutorial docsTEACH AUTHGUARD TO AUTHENTICATE部分。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
     let url: string = state.url; 

     return this.checkLogin(url); 
     } 

     checkLogin(url: string): boolean { 
     if (this.authService.isLoggedIn) { return true; } 

     // Store the attempted URL for redirecting 
     this.authService.redirectUrl = url; 

     // Navigate to the login page with extras 
     this.router.navigate(['/login']); 
     return false; 
} 
+0

感謝您的回覆,但我不想重定向到登錄或某個頁面。我想在用戶從page1導航到這個頁面2時清除緩存,並且我希望在從其他頁面導航到此頁面時保留緩存。 – Kashyap

+0

當canActivate被執行時,頁面url仍然是前一頁。所以我可以通過window.location.href獲取網址。但想看看有沒有這樣做的角度方式。 – Kashyap

+0

state.url會給透明url.u想要當前url用戶ActivatedrouteSnapshot「snapshot」屬性。 –