我有一个新的Angular 2应用程序(最新的完整版本),我想知道用户每次导航时的当前url和目标url,无论是通过点击链接还是在浏览器的地址栏中键入。我希望能够决定是否允许它们转到url,如果不允许,则将它们放回原始url。我希望地址栏中的url在这两种情况下都能更新。我尝试了以下方法,但这些方法并没有提供oldUrl,只提供了NewUrl。
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) )实现这一点。
请帮帮忙。
发布于 2017-05-16 19:36:42
试试下面的卫士,它会给出包含你想要的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??") ;
}
}https://stackoverflow.com/questions/39779896
复制相似问题