2016-09-29 79 views
2

我有一個新的Angular 2應用程序(最新完整版),每次用戶瀏覽是否通過點擊鏈接或在瀏覽器的地址欄中輸入,我都想知道當前的url和目標url。我希望能夠決定是否允許他們轉到網址,如果不能將他們放回原始網址。無論在哪種情況下,我都希望地址欄中的網址可以更新。我嘗試了以下方法,但這些並沒有提供oldUrl只有NewUrl。Angular 2導航事件

router.events.subscribe((event: NavigationEvent) => 
    { 
     if (event instanceof NavigationStart) 
     { 

     } 

     if (event instanceof NavigationEnd) 
     { 

     } 

     if (event instanceof NavigationCancel) 
     { 

     } 
    }); 

我很容易就與範圍,角1實現這一目標。$在( '$ locationChangeStart',函數(事件,NEWURL,OLDURL)和範圍。$在( '$ routeChangeSuccess',函數(EVT ,NEWURL,OLDURL)。

請幫助。

+0

查看CanActivate用於確定用戶是否被允許導航的警戒。不知道如何抓住目標和最後一個網址。 https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard – cboston

+0

感謝cboston回覆。我已經用CanActivate設置了一名警衛,但是它並沒有給我newUrl和oldUrl。 – LanceM

回答

0

嘗試後保護,它給原狀態數和newState包含要的URL。在你的用例取決於是否有幫助。

export class PendingChangesGuard implements CanDeactivate<Shipments> { 
    constructor(@Inject(ComponentService) private _service:ComponentService){} 
    @HostListener('window:beforeunload') 
    canDeactivate(component: Shipments, 
        currentRoute: ActivatedRouteSnapshot, 
        currentState: RouterStateSnapshot, 
        nextState: RouterStateSnapshot): Observable<boolean> | boolean { 
     console.log(nextState) 
     return this._service.getSelectedMaterials().length < 0 ? true : window.confirm("Are you sure you want to Exit??") ; 
    } 
}