ui-route 解决不工作 [英] ui-route resolve not working
问题描述
我的应用程序需要一些基本数据才能启动.这就是为什么我创建了一个服务,并将其用作该公共数据的模型,以便所有控制器都可以访问它.我正在尝试使用 ui-route 的 reslove 功能解析服务,该功能表示如果我返回一个承诺,那么它将在控制器执行开始之前解决,但它对我不起作用.这是我的代码
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
服务:
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'];
路线:
.state('temp', {
url: 'temp',
templateUrl: '/temp',
controller: 'temp',
resolve: {
data: function (data) {
return data.getData();
}
}
})
控制器:
var temp = function(data, $scope){
console.log('asad');
$scope.showLoading = true;
$scope.prefixes = data.something; //not working
$scope.lists = data;
};
temp.$inject = ['data', '$scope'];
推荐答案
首先,使用 plunker 会更容易.
first, it will be easier to work with a plunker.
但似乎函数 getData 没有返回任何承诺.
But it seems like the function getData doesn't return any promise.
我会将 getData() 更改为:
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;
};
顺便说一句,我也会将 resolveData() 改为:
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;
};
这篇关于ui-route 解决不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!