3

I think I have a syntax error in my code, but I am not entirely sure. Basically when I call a function on the service, it returns the code rather than the return value of the function.

This is the service ...

(function (){
'use strict';

var products = function($http){

    var getProducts = function () {
        return $http.get(getDataUrl)
            .then(function (response) {
                return response.data;
            });
    };

    //Make functions public
    return {
        getProducts: getProducts
    };
};

var module = angular.module("shop");
module.factory("products", products);
module.constant("getDataUrl", "xxx")

}());

This is the controller than invokes the product service ...

 (function () {
'use strict';

angular
    .module("shop")
    .controller("ProductController", ProductController);

function ProductController($scope, cart, $routeParams, products) {

    // $scope.product = products.getProducts;
    // console.log($scope.product);

    var productId = getProductIdFromUrl();
    console.log("productId: " + productId);

    console.log("products: " + products.getProducts);

    function getProductIdFromUrl(){
        return $routeParams.productId;
    }

}

})();

Now rather than returning the JSON data that I am expecting, the console.log is just printing the the functions code. Anyone any ideas?

The console.log prints the following ...

 products: function () {
        return $http.get(getDataUrl)
            .then(function (response) {
                return response.data;
            });
    }

1 Answer 1

7

Yep, you do have a syntax error, right here:

console.log("products: " + products.getProducts);

That should be:

console.log("products: " + products.getProducts());

HOWEVER that is not going to log a list of products, it's going to log a promise object, which is what $http.get().then() returns. You need to re-read the documentation for $http and also read more about promises and how they work. Your code is non-functional as-is. This article explains why: http://blog.ninja-squad.com/2015/05/28/angularjs-promises/

Sign up to request clarification or add additional context in comments.

Comments

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.