我已经在网上搜索了几天。我了解,如果您在解析中重定向($state.go 等),转换将被取消,所有解析都会再次运行。
但是,如果我只需要防止进入某个子状态怎么办。而且我在解析中获取我非常不需要也不想再次获取的数据。
我不敢相信这对人们来说是一个不寻常的场景。如果有人有想法,请帮助我让这个 plnkr 工作!
http://plnkr.co/edit/gFDcRqoPXKbD1ZZwylO9?p=preview
var app = angular.module('plunker', ['ui.router']);
app.config(['$stateProvider', function($stateProvider){
$stateProvider
.state('posts', {
url: "/posts",
templateUrl: "posts-index.html",
controller: "PostsIndexController",
resolve: {
posts: function(Post) {
console.log('Hi');
return Post.all()
}
},
onEnter: function($state, posts) {
if (posts.length > 1 && confirm("Redirect to first post?")) {
console.log('Howdy')
// $state.go('posts.show', { postId: 3 });
}
}
})
.state('posts.empty', {
templateUrl: "posts-show.html",
resolve: {
saySomething: function($state) {
console.log('Yo')
}
}
})
.state('posts.show', {
url: "/:postId",
templateUrl: "posts-show.html",
controller: "PostsShowController",
resolve: {
post: function($stateParams, $q, Post) {
console.log($stateParams);
return Post.find($stateParams.postId)
}
},
onEnter: function($stateParams, $state) {
if ($stateParams.postId === '1') {
console.log('Now')
return $state.go("posts.empty")
}
}
})
}]);
app.controller("PostsIndexController", function($scope, posts){
$scope.posts = posts
})
app.controller("PostsShowController", function($scope, post){
$scope.post = post
})
app.run(function($rootScope, $state) {
$rootScope.$on('$stateChangeError', function(evt, to, toParams, from, fromParams, error) {
console.log(to, toParams)
console.log(from, fromParams)
if (error.redirectTo) {
$state.transitionTo(error.redirectTo, error.redirectToParams);
} else {
// $state.go('error', {status: error.status})
}
})
})
app.factory('Post', function(){
return {
all: function() {
return [
{ id: 1, title: "Post 1" },
{ id: 2, title: "Post 2" },
{ id: 3, title: "Post 3" }
]
},
find: function(id) {
return _(this.all()).findWhere({id: +id})
}
}
})