0

I'm trying to do this:

app.service('productsService', ['$http', productsService]);

function productsService($http){

    return {
        getProducts: getProducts
    }

    var _products = [];

    function getProducts(){

        $http.get('http://localhost:4000')
            .then(function(data){
                _products = data;
            });
        }
}

But at the then callback _products is an undefined variable.

What is the correct way to set _products value from the then callback?

1 Answer 1

1

You need to set the variable before the return statement.

app.service('productsService', ['$http', productsService]);

function productsService($http){
    var _products = [];

    return {
        getProducts: getProducts
    }

    //var _products = []; this will never run

    function getProducts(){

        $http.get('http://localhost:4000')
            .then(function(data){
                _products = data;
            });
        }
}
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.