I have a problem with a promise. This is the controller for a detail page. I want to get the item details from a web service (or from the local store if they are stored).
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);
});
}
};
})
The first time (the items aren't in the local store) all works well because the getAll method return a promise, but the second time it doesn't return a promice so I get
Cannot read property 'then' of undefined
How I can solve this?