javascript - AngularJS Bypass promise if data is present in cache -
i sending ajax request fetch data server , storing in local variable. inside service. in controller using promise data when needed. first time works because no cache detected , promise returned next time onwards not returning promise service function , hence javascript error.
my function in service is:
getproductdetails: function(product) { if(!productdetailsarr[product.id]) { if (!promiseproductdetails) { // $http returns promise, has function, returns promise promiseproductdetails = $http.get(product.id + '/productdetails.json').then(function(response) { productdetailsarr[product.id] = response; return productdetailsarr[product.id]; }); } // return promise controller return promiseproductdetails; } else { return productdetailsarr[product.id]; } }
in controller have invoked above function following code:
servicedata.getproductdetails($scope.product).then(function(data) { $scope.productdetails = data; });
so on second time onwards js error:
typeerror: servicedata.getproductdetails(...).then not function
any idea how fix this.
what should doing returning promise. in case, can return resolved promise. can read more here.
if(!productdetailsarr[product.id]) { if (!promiseproductdetails) { // $http returns promise, has function, returns promise promiseproductdetails = $http.get(product.id + '/productdetails.json').then(function(response) { productdetailsarr[product.id] = response; return productdetailsarr[product.id]; }); } // return promise controller return promiseproductdetails; } else { var deferred = $q.defer(); deferred.resolve(productdetailsarr[product.id]); return deferred.promise; }
Comments
Post a Comment