2016-09-29 73 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??") ; 
    } 
}