Ant*_*ine 6 javascript angularjs angular-ui-router
我是AngularJS和ui-router的初学者,我正试图在未找到的资源上处理404.我想在不更改地址栏中的URL的情况下显示错误.
我已经配置了我的状态:
app.config([
"$stateProvider", function($stateProvider) {
$stateProvider
.state("home", {
url: "/",
templateUrl: "app/views/home/home.html"
})
.state("listings", {
abstract: true,
url: "/listings",
templateUrl: "app/views/listings/listings.html"
})
.state("listings.list", {
url: "",
templateUrl: "app/views/listings/listings.list.html",
})
.state("listings.details", {
url: "/{id:.{36}}",
templateUrl: "app/views/listings/listings.details.html",
resolve: {
listing: [
"$stateParams", "listingRepository",
function($stateParams, repository) {
return repository.get({ id: $stateParams.id }).$promise;
}
]
}
})
.state("listings.notFound", {
url: "/404",
template: "Listing not found"
});
}
]);
Run Code Online (Sandbox Code Playgroud)
(我实际上是在使用TypeScript,但我试图将上面的内容改为纯JavaScript)
例如,如果我导航到以下url:
http://localhost:12345/listings/bef8a5dc-0f9e-4541-8446-4ebb10882045
那应该打开listing.details状态.但是,如果该资源不存在,则从resolve函数返回的promise将失败,并在404中捕获:
app.run([
"$rootScope", "$state",
function($rootScope, $state) {
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
event.preventDefault();
if (error.status === 404) {
$state.go("^.notFound", null, { location: true, relative: toState });
}
});
}
]);
Run Code Online (Sandbox Code Playgroud)
我在这里要做的是转到listing.notFound状态,而不更改地址栏中的目标URL.我使用相对路径,因为我想将此逻辑重用于其他资源.
但是,我得到一个例外:
路径'^ .notFound'对州'listing.details'无效
发生此错误是因为$ stateChangeError事件给出的toState参数不知道其父级,即toState.parent未定义.在ui-router的transitionTo函数中,我可以看到作为参数给出的对象是to.self,它只提供信息的子集.使用relative: $state.get(toState.name)也没有帮助,因为内部ui-router再次返回state.self
我想避免维护一个绝对路径列表,并重写在状态层次结构中导航的逻辑(无论它有多简单,DRY和所有这些).
我是不是错了,是否还有另一种处理404的正确方法?如果没有,最好的方法是什么?
最好用它$urlRouterProvider来处理这个异常
app.config([
"$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/404');
// define states
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2192 次 |
| 最近记录: |