Reputation: 9212
I have a ProductService that fetches data and gives to ProductsController. This is the code.
sampleApp.factory('ProductService', ['$http', function ($http){
var req = {
method: 'POST',
url: 'ProductData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
return {
GetProducts: function () {
return $http(req);
},
GetDetailInfo: function (ProductID) {
// HOW TO IMPLEMENT THIS
}
};
}]);
sampleApp.controller('ProductsController', function ($scope, $routeParams, ProductService, ShoppingCartService) {
$scope.Products = [];
$scope.GetProducts = function() {
ProductService.GetProducts().then(
function(response) {
if (response.data !== undefined) {
//alert (response.data);
console.log(response.data);
$scope.Products = response.data;
}
else {
alert ('undefined data');
}
},
function(Error) {
alert ('error worng');
}
);
};
$scope.GetProducts();
});
Now i want to implement one more function in service that gives the detail information about a product. But since $scope.Products is not available in ProductService, i can not loop and get data for desired ProductID.
I want to implement that function in ProductService only not in ProductsController, becuase some other service(that needs product data) will be using this ProductService.
How to solve this problem?
If there is any better architecture to achieve the same, that is also welcome.
Upvotes: 1
Views: 4085
Reputation: 18566
You need to rewrite the GetProducts
in your service to store the products data inside the service.
Instead of returning $http(req)
, resolve the promise inside the service.
In the success callback, store the response data in the service by declaring a variable inside the service. Then return the promise to the controller.
This should solve your issue.
Sample code:
sampleApp.factory('ProductService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'ProductData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var productService = {};
productService.products = [];
return {
GetProducts: function () {
var defer = $q.defer();
$http(req).then(function(response) {
productService.products = response.data;
defer.resolve(productService.products);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
},
GetDetailInfo: function (ProductID) {
// HOW TO IMPLEMENT THIS
// productService.products is available here. Loop through and find.
}
};
}]);
In your controller:
$scope.GetProducts = function() {
ProductService.GetProducts().then(
function(response) {
$scope.Products = response;
}, function(error) {
// your error code here
});
};
Upvotes: 1