假设我们在配置中定义了路由:
$routeProvider
.when('/person/:person_id', {
controller: 'person',
templateUrl: 'partials/person.html',
resolve: {
data: ['api', '$route',
function(api, $route) {
return api('api/person/page/' + $route.current.params.person_id);
}
]
}
})
.otherwise({
controller: 'error',
templateUrl: 'partials/404.html',
});
此外,我们可以确定所有 Controller 、 View 和 API 端点都存在。
现在,当我们导航到不存在的路由时,例如:blahblah/foobar
,路由器的行为正如我所期望的:运行“错误” ' Controller ,并显示 404.html。
但是,如果 API 端点返回 404 时 /person/:person_id
的解析失败(因为该人不存在) - Angular 表现出一些不稳定的行为,它既不会运行 ' person' Controller ,也不是 'error' Controller ,但可以正确显示 404 部分。
我想知道如何让 Angular 在解析失败时运行“错误” Controller ,就像路径不存在时一样。
-编辑-
请记住,由于应用程序要求,我无法重定向。
路由器需要停留在错误的 URL 上,而不是重定向到专用的 404 路由。
最佳答案
根据 docs对于$routeProvider
,如果解析 block 失败,将会有一个$routeChangeError
事件。您可以将监听器连接到该事件并手动重定向到错误页面,但这需要您向其添加 url。
.otherwise ({
url: '/ohmy',
controller: 'error',
templateUrl: 'partials/404.html',
});
某个地方,可能在 module.run
函数中
angular.module('myModule').run(['$rootScope', '$location',
function($rootScope, $location) {
$rootScope.$on('$routeChangeError', function() {
$location.path('/ohmy');
});
}]);
关于javascript - 如果另一个 Controller 上的解析失败,AngularJS 'otherwise' Controller 不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25636582/