Angular 角度2导航事件
我有一个新的Angular 2应用程序(最新的完整版本),我想知道用户每次导航时的当前url和目标url,无论是通过单击链接还是在浏览器的地址栏中键入。我希望能够决定他们是否被允许进入该url,如果不允许,将他们放回原始url。我希望地址栏中的url在任何情况下都能更新。我尝试了以下方法,但它们并没有提供旧的URL,只提供了新的URLAngular 角度2导航事件,angular,routing,navigation,Angular,Routing,Navigation,我有一个新的Angular 2应用程序(最新的完整版本),我想知道用户每次导航时的当前url和目标url,无论是通过单击链接还是在浏览器的地址栏中键入。我希望能够决定他们是否被允许进入该url,如果不允许,将他们放回原始url。我希望地址栏中的url在任何情况下都能更新。我尝试了以下方法,但它们并没有提供旧的URL,只提供了新的URL router.events.subscribe((event: NavigationEvent) => { if (even
router.events.subscribe((event: NavigationEvent) =>
{
if (event instanceof NavigationStart)
{
}
if (event instanceof NavigationEnd)
{
}
if (event instanceof NavigationCancel)
{
}
});
我很容易在Angular 1中使用scope.$on('locationChangeStart',function(event,newUrl,oldUrl)和scope.$on('routeChangeSuccess',function(evt,newUrl,oldUrl)实现这一点
请提供帮助。尝试以下保护,它提供包含所需URL的oldState和newState。如果有帮助,则取决于您的用例
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??") ;
}
}
导出类PendingChangesGuard实现CanDeactivate{
构造函数(@Inject(ComponentService)private _-service:ComponentService){}
@HostListener('窗口:在卸载之前')
canDeactivate(组件:装运、,
currentRoute:ActivatedRouteSnapshot,
currentState:RouterStateSnapshot,
nextState:RouterStateSnapshot):可观察的|布尔值{
console.log(nextState)
返回此内容。_service.getSelectedMaterials()。长度<0?true:window.confirm(“是否确实要退出?”);
}
}
查看CanActivate guard以确定是否允许用户导航。但不确定如何获取目标和最后一个url。感谢cboston的回复。我已经使用CanActivate设置了一个guard,但它没有提供新url和旧url。