【问题标题】:AngularJS: Get Url before redirectAngularJS:在重定向之前获取网址
【发布时间】:2020-03-04 14:59:16
【问题描述】:

我为所有错误的 URL 定义了一个状态

.state('404', { 
    url: '/404',
    data: { title: 'Page not found' },
    templateUrl: errorHandlerTemplate,
    parent: 'authenticated' 
})

我设置了重定向以使其正常工作

$urlRouterProvider.otherwise('/404');

我想获取用户在重定向发生之前尝试输入的原始 URL。

$transitions.onBefore({ entering: '404' }, function(trans) {
    console.log(trans.from().name);
    console.log(trans.to().name);
});

'trans.to().name' 似乎总是保存值 '404',这是重定向后的最终 URL。有没有办法获取被丢弃的原始Url?

【问题讨论】:

  • 如果 UI 路由器进行了重定向,那么就有可能获得之前的 URL。如果服务器进行了重定向,那么就没有机会了。你能澄清一下吗?
  • '$urlRouterProvider.otherwise('/404')' 是客户端的重定向

标签: javascript angularjs angular-ui-router transition


【解决方案1】:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
    console.log(fromState, fromParams);
}

$stateChangeStart 在过渡开始时触发

fromStatefromParams 足以在重定向之前获取url。

For more info on $stateChangeStart

【讨论】:

  • $transitions 服务已弃用 $rootScope。您确实有一个 onBefore 事件,但 'from' 和 'to' 分别显示最后一个有效的 Url 和 '/404'。被重定向到 /404 的无效 Url 在两者之间被吃掉了
  • 你为什么要那个无效的网址?!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多