1

I created a helper service to wrap the $http.get.

self.apiGet = function (url, success, failure, always) {
           
            $http.get(url)
                .then(function (result) {
                    success(result);
                    if (always != null)
                        always();
                }, function (result) {
                    if (failure != null) {
                        failure(result);
                    }
                    else {

                    }
                    if (always != null)
                        always();
                });
        }

In my controller class, the data is not returned to the view when calling getData(val). the data is returned from the api when I debug it.

 $scope.getData = function (val) {
        return helper.apiGet(url,
            function (result) {
                return result.data;
            });
    }; 

7
  • Is your angular app and the api on the same domain? Commented Jan 1, 2016 at 10:00
  • they are not in the same domain. I don't think it is csrf related as I can see the data. I just can't figure out why it is returned to the view. Commented Jan 1, 2016 at 10:05
  • You mean you have cors enabled in the other app (the api)? csrf and cors are different but I guess you know that already. Commented Jan 1, 2016 at 10:07
  • You need to show your view code so we understand your intentions. But I suspect that you are over thinking this ... Commented Jan 1, 2016 at 10:09
  • Well, your apiGet() function doesn't return anything. You're reinventing promises poorly. Your apiGet() function doesn't do anything that promises don't allow to do natively, and in a standard way. Read this article, to understand the traps of promises that you fell into: blog.ninja-squad.com/2015/05/28/angularjs-promises Commented Jan 1, 2016 at 10:09

1 Answer 1

4

You should just use promises properly. So the service becomes:

self.apiGet = function(url) {
    return $http.get(url).then(function(result) {
        return result.data;
    });
};

... and it's consumed in controller like this:

helper.apiGet(url).then(function(data) {
    $scope.data = data;
});
Sign up to request clarification or add additional context in comments.

2 Comments

I use Typeahead in my view which requires calling function in my controller, I can't just use the $scope here.
Doesn't matter. The point is that you just return promise from the service. Then you use it whatever way you need. In your case you can call function instead of $scope.data = data;.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.