1

I guess the $http.get part is not working . Here is my code :

.controller('home', function($scope, request){
            $scope.list = request.get(baseUrl);
    })
.factory('request', function($http){
        var get = function(url){
            $http.get(url).success(function(data){
                console.log(data); 
                return data; //returns nothing
            });
        }

        return {
            get : get
        }
    });
8
  • Define the success callback function like this function(data, status, headers, config) and then print each argument to the console and let's know the output. Commented Sep 4, 2014 at 16:53
  • @bmleite the success function actually isn't executing I mean $http.get isn't working Commented Sep 4, 2014 at 16:59
  • Why do you say "$http.get isn't working"? Do you see any error in the console? Commented Sep 4, 2014 at 17:05
  • nope i tried printing console.log("test") inside the success function but it didn't print anything Commented Sep 4, 2014 at 17:08
  • 1
    $http.get is an async function, you need to return a promise not the data. Commented Sep 4, 2014 at 17:41

2 Answers 2

3

Try this.

.factory('request', function($http){
    var get = function(url){
        return $http.get(url).success(function(data){
            return data;
        });
    }

    return {
        get : get
    }
});

Update your controller.

request.get(url).then(function (data) {

  $scope.data = data;

}, function (response) {
     // handle error
});

http://plnkr.co/edit/eWXckgiwPNCGMlP0LQyk?p=preview

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

1 Comment

The controller is wrong too: request.get(baseUrl).then ( function ( data ) { $scope.list = data }); Which you did in the plunker, I guess I should have looked at that first... sorry.
1

Generally speaking, your function doesn't return anything at all - if I were to call request.get(), it would return undefined. You want something like

.controller('home', function($scope, request){
    request.get(baseUrl).then(function(data){ // I prefer then and catch semantics
        $scope.list = data;                   // as they're standard promises form
    })['catch'](function (err){console.log(err)});
})
.factory('request', function($http){
    var get = function(url){
        return $http.get(url).then(function(data){
            console.log(data); 
            return data; 
        });
    }
    return {
        get : get
    }
});

Although this is unnecessary obfuscation for a simple case (i'd just put the $http.get().then().catch() stuff in the controller instead of a factory.

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.