我有一个承诺的问题。这是详细信息页面的控制器。我希望从Web服务(或存储的本地商店)获取项目详细信息。
app.controller('ProductCtrl', function($scope, productsService) {
//load the product by id from productService
productsService.get("CODE-1111").then(function(result){
$scope.currProduct = result;
$scope.currProductSizes = $scope.currProduct.sizes;
});
}
app.service('productsService', function($http, localStorageService){
var _key = 'myProducts'
var _storedData = []
var self = this;
self.get = function(id){
var i = 0;
return self.getAll().then(function(result) {
//get the item by id
_storedData = result;
for(i=0;i<_storedData.length;i++){
if(_storedData[i].id == id)
break;
}
return _storedData[i];
});
}
self.getAll = function() {
_storedData = localStorageService.get(_key);
if(_storedData != null){
**//How return a promise here? Or how I can handle it**
return _storedData instanceof Array ? _storedData : [_storedData];
}
else{
var url = baseUrl + "api/GetStyles";
return $http({method: 'GET', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }})
.then(function(response) {
_storedData = mapToProducts(JSON.parse(response.data));
return _storedData;
},
function(response) {
console.log(response.status);
});
}
};
})
第一次(项目不在本地商店中)一切正常,因为getAll方法返回一个promise,但第二次它没有返回promice,所以我得到了
Cannot read property 'then' of undefined
我如何解决这个问题?
答案 0 :(得分:2)
你可以回复这样的承诺:
return $q.when(_storedData instanceof Array ? _storedData : [_storedData])
;
答案 1 :(得分:-1)
你需要在你的get和getAll函数中响应一个promise,我改变你的函数来做到这一点:
app.service('productsService', ['$http', '$q', 'localStorageService', function($http, $q, localStorageService){
var q = $q;
var _key = 'myProducts';
var _storedData = [];
var self = this;
self.get = function(id){
var deferred = q.defer(); //Initialize your own promise
var i = 0;
self.getAll().then(function(result) {
//get the item by id
_storedData = result;
for(i=0;i<_storedData.length;i++){
if(_storedData[i].id == id)
break;
}
return deferred.resolve(_storedData[i]); //This is your response for success
}).catch(function(error) {
deferred.reject(error); //This is your response for failure
});
return deferred.promise; //return the promise
}
self.getAll = function() {
var deferred = q.defer(); //Initialize your own promise
_storedData = localStorageService.get(_key);
if(_storedData != null){
var data = _storedData instanceof Array ? _storedData : [_storedData];
deferred.resolve(data);
} else {
var url = baseUrl + "api/GetStyles";
$http({method: 'GET', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }}).then(function(response) {
_storedData = mapToProducts(JSON.parse(response.data));
deferred.resolve(_storedData); //This is your response for success
}, function(error) {
deferred.reject(error); //This is your response for failure
});
}
return deferred.promise;
};
}]);