我尝试使用 resolve 在父状态上加载一些数据,并在应用程序运行时将用户重定向到默认状态:
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url: '/',
template: '<div><a ui-sref="home">Start App</a> <a ui-sref="home.main">Home</a> <a ui-sref="home.other">Other state</a><div ui-view>Loading...</div></div>',
resolve: {
user: ['$timeout', '$q',
function($timeout, $q) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedVal = promise.then(function() {
console.log('$timeout executed');
return {Id: 12, email: 'some@email.com', name: 'some name'};
}, function() {
console.log('Error happend');
});
$timeout(function() {
deferred.resolve();
}, 2000);
return resolvedVal;
}]
//user: function() {return {id: 222, name: 'testname', email: 'test@em.ail'}; }
},
controller: ['$scope', 'user', function($scope, user) {
$scope.user = user;
}]
});
$stateProvider.state('home.other', {
url: 'other',
template: '<div>Your name is {{user.name}}, and email is {{user.email}}</div><div>This is other state of application, I try to make it open as default when application starts, by calling to $state.transitionTo() function in app.run() method</div>',
resolve: {
someObj: function() {
console.log('hello');
return {someProp: 'someValue'};
}
},
controller: ['$scope', 'user', function($scope, user) {
$scope.user = user;
}]
});
}]);
app.run(['$state', '$rootScope', function ($state, $rootScope) {
$state.go('home.other');
}]);
并且这不会改变地址栏中的 url 并且不会显示 home.other state 的模板(尽管 home.state 的 resolve 函数被执行并且控制台中有'hello')。 但是,当我在 resolve 中评论 promise 函数,而不是将返回对象的简单函数放在那里时,应用程序按预期重定向。
此外,尝试做 $http 请求而不是 $timeout,它实际上会在那里,但也没有运气。
最佳答案
然后回答我自己的问题——由于摘要周期开始处理请求的 url,在调用 $state.go('home.other') 之后发生了不需要的行为,并且由于解析函数创建了延迟对象,尽管该对象已解析,状态引擎已经传递到请求的 url 的状态。所以为了防止这种情况,我使用了下面解释的技术:
如果您需要在应用程序启动时在某些情况下放弃执行请求的 url 的状态解析,您可以使用 $stateChangeStart 事件,如下所示:
app.run(['$state', '$rootScope', '$timeout', function ($state, $rootScope, $timeout) {
var appStarted = 0; // flag to redirect only once when app is started
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
if(appStarted) return;
appStarted = 1;
event.preventDefault(); //prevents from resolving requested url
$state.go('home.other'); //redirects to 'home.other' state url
});
}]);
关于javascript - 为什么 $state.go 在目标状态或其父级通过 promise 解析时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22050215/