1

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.

5
  • Why don't you store the Products array in the service instead? Commented Apr 3, 2015 at 8:01
  • I can do that too. But according to AngularJS best practice and SO suggestions its always good store Variables in controller. Correct me if i am wrong? Commented Apr 3, 2015 at 8:04
  • No. Controller is a good place to store VM specific to that view. If data need to be persisted and shared across multiple controllers/views then service is the best place to store the data @DeveshAgrawal Commented Apr 3, 2015 at 8:11
  • Do not access the controller in your service - that breaks the MVC pattern Commented Apr 3, 2015 at 8:12
  • just pass it the id. Commented Apr 3, 2015 at 8:35

1 Answer 1

1

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
          });
    };
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. Can you help me in what changes i need to make in controller now, so the Products are available in controller also?
Updated above in the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.