问题
My Application needs a some basic data to start. That's why i created a service and I am using it as model for that common data so that it can be accessible to all the controllers. I am trying to resolve the service using ui-route's reslove functionality that says if I return a promise then it will be resolved before the controller's execution begin but it is not working for me. here is my code
service:
var Data = function ($q, $http) {
var list = {};
var cachedData;
var resolveData;
resolveData = function () {
return $http.get('/api/data')
.then(function (response) {
var deferred = $q.defer();
deferred.resolve(list.setData(response.data));
return deferred.promise;
}, function (response) {
});
};
list.getData = function () {
if (cachedData) {
return cachedData;
}
else {
resolveData();
}
};
list.setData = function (data) {
cachedData = data;
return data;
};
return list;
};
Data.$inject = ['$q', '$http'];
Route:
.state('temp', {
url: 'temp',
templateUrl: '/temp',
controller: 'temp',
resolve: {
data: function (data) {
return data.getData();
}
}
})
Controller:
var temp = function(data, $scope){
console.log('asad');
$scope.showLoading = true;
$scope.prefixes = data.something; //not working
$scope.lists = data;
};
temp.$inject = ['data', '$scope'];
回答1:
first, it will be easier to work with a plunker.
But it seems like the function getData doesn't return any promise.
I will change getData() to something like:
list.getData = function () {
var deferred = $q.defer();
if (cachedData) {
deferred.resolve(cachedData);
} else {
resolveData().then(deferred.resolve).catch(deferred.reject);
}
return deferred.promise;
};
btw, I will also change resolveData() to:
resolveData = function () {
var deferred = $q.defer();
$http.get('/api/data')
.then(function (response) {
list.setData(response.data);
deferred.resolve(response.data);
});
return deferred.promise;
};
来源:https://stackoverflow.com/questions/35668509/ui-route-resolve-not-working