我尝试使用解析加载父状态上的一些数据,并在应用程序运行时将用户重定向到默认状态,如下所示:
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: '[email protected] /cdn-cgi/l/email-protection', name: 'some name'};
}, function() {
console.log('Error happend');
});
$timeout(function() {
deferred.resolve();
}, 2000);
return resolvedVal;
}]
//user: function() {return {id: 222, name: 'testname', email: '[email protected] /cdn-cgi/l/email-protection'}; }
},
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 状态的模板(尽管执行了 home.state 的解析函数并且控制台中有“hello”)。
但是,当我在解析中评论 Promise 函数时,而是将简单的函数返回对象应用程序按预期重定向。
另外,尝试执行 $http 请求而不是 $timeout ,该请求实际上会在那里,但也没有运气。