【问题标题】:Angular 2 Navigation EventsAngular 2 导航事件
【发布时间】:2017-02-08 08:17:57
【问题描述】:

我有一个新的 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 )。

请帮忙。

【问题讨论】:

  • 查看 CanActivate 守卫以确定是否允许用户导航。不确定如何获取目标和最后一个 url。 angular.io/docs/ts/latest/guide/…
  • 感谢 cboston 的回复。我已经用 CanActivate 设置了一个守卫,但它没有给我 newUrl 和 oldUrl。

标签: angular routing navigation


【解决方案1】:

试试下面的 Guard,它会给出包含你想要的 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??") ;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多