【发布时间】:2018-08-10 16:35:55
【问题描述】:
我有一个使用 ui-router 的 angularJS 组件,它有 2 个简单的路由状态。
export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('details', {
url: '/',
template: '<div>...</div>'
})
.state('pdf', {
url: '/viewpdf',
template: '<pdf-viewer></pdf-viewer>'
});
$urlRouterProvider.otherwise(function ($injector, $location) {
var $state = $injector.get("$state");
$state.go("details");
});
}
在 details 视图中,我有一个控制器,它获取 PDF 文档,然后使用 $state.go('pdf'); 在回调中更改路由状态
在 pdf 视图中,我有一个 ui-sref 链接可以返回到详细信息视图:
<a ui-sref="details">Back to Details</a>
间歇性地,当我按下 Back to Details 按钮时,它会从 page.js 中抛出一个错误并且不会更改路由状态。
Uncaught TypeError: Cannot read property '0' of undefined at new Context (page.js:208) at Function.page.replace (page.js:154) at onpopstate (page.js:347) at B (history.min.js:21) at history.min.js:22 Context @ page.js:208 page.replace @ page.js:154 onpopstate @ page.js:347 B @ history.min.js:21 (anonymous) @ history.min.js:22
查找我得到的错误源:(page.js: 208)
/**
* Initialize a new "request" `Context`
* with the given `path` and optional initial `state`.
*
* @param {String} path
* @param {Object} state
* @api public
*/
function Context(path, state) {
/* ERROR STACK ENDS ON THIS LINE */
if ('/' == path[0] && 0 != path.indexOf(base)) path = base + path;
/* END */
var i = path.indexOf('?');
this.canonicalPath = path;
this.path = path.replace(base, '') || '/';
this.title = document.title;
this.state = state || {};
this.state.path = path;
this.querystring = ~i ? path.slice(i + 1) : '';
this.pathname = ~i ? path.slice(0, i) : path;
this.params = [];
// fragment
this.hash = '';
if (!~this.path.indexOf('#')) return;
var parts = this.path.split('#');
this.path = parts[0];
this.hash = parts[1] || '';
this.querystring = this.querystring.split('#')[0];
}
url 和视图保持在/viewpdf。如果我等待几秒钟,然后再次点击返回按钮,它将正常工作。
是什么导致了这种行为,我该如何解决?
编辑
我应该澄清一下,当我提到后退按钮时,我指的是/viewpdf 视图中的 Back to Details 按钮,而不是浏览器的后退按钮。浏览器后退按钮没有出现该错误。
【问题讨论】:
-
几个问题:1)什么是page.js? 2) 你为什么不直接使用
$urlRouterProvider.otherwise('details');,因为你没有在其他功能中使用任何高级功能? -
我没有显式添加page.js,它看起来像是ui-router的依赖。添加了 else 回调以解决其他一些路由问题(我现在不记得是哪个了?)。这是问题的简化版本,而不是整个应用程序。
-
另外,我的理解是
ui-sref应该以otherwise不发挥作用的方式设置路由状态。后退按钮简单地加载其他状态是不正确的。
标签: javascript angularjs angular-ui-router page.js