首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 2导航事件

Angular 2导航事件
EN

Stack Overflow用户
提问于 2016-09-30 04:57:05
回答 1查看 880关注 0票数 2

我有一个新的Angular 2应用程序(最新的完整版本),我想知道用户每次导航时的当前url和目标url,无论是通过点击链接还是在浏览器的地址栏中键入。我希望能够决定是否允许它们转到url,如果不允许,则将它们放回原始url。我希望地址栏中的url在这两种情况下都能更新。我尝试了以下方法,但这些方法并没有提供oldUrl,只提供了NewUrl。

代码语言:javascript
复制
    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) )实现这一点。

请帮帮忙。

EN

回答 1

Stack Overflow用户

发布于 2017-05-16 19:36:42

试试下面的卫士,它会给出包含你想要的URL的oldState和newState。取决于你的用例,如果有用的话。

代码语言:javascript
复制
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??") ;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39779896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档