1

I have an HTTP request setup as a promise in a .factory and would like to send the result to a controller. However I am stuck with getting the data out of promise and into somewhere I can use it.

.controller

.controller('MainCtrl', function ($scope, Main, User) {
    $scope.feedResult = function () {
        var feeds = [];
        return Main.feed(key).success(function (data, status, headers, config) {
            for (var i = 0; i < data.length; i += 1)
            {
                feeds.push(data[i]);
            }
            return feeds;
        }).error(function (data, status, headers, config) {
            console.log("This was an error back from the server");
            console.log(data);
            return data;
        });
    }();
})

and the .factory

        feed: function (token) {
            return $http({
                url: 'http://myserver.com/feed',
                method: 'GET',
                data: {
                    auth_code: token,
                    per_page: 10
                }
            }).success(function (data, status, headers, config) {
                for (var i = 0; i < data.length; i += 1)
                {
                    feeds.push(data[i]);
                }
                return feeds;
            }).error(function (data, status, headers, config) {
                console.log("This was an error back from the server");
                console.log(data);
                return data;
            });
        },

Mo matter how I seem to try putting things into a scope I always seem to end up with the promise object. Can someone help me out?

0

1 Answer 1

1

The success or error method will always return a promise (it wraps your return value into a new promise). You shoudl set the value on the scope from within the success/error callback:

.controller('MainCtrl', function ($scope, Main, User) {
    $scope.feedResult = [];
    Main.feed(key).success(function (data, status, headers, config) {
        for (var i = 0; i < data.length; i += 1)
        {
             $scope.feedResult.push(data[i]);
        }
    }).error(function (data, status, headers, config) {
        console.log("This was an error back from the server");
        console.log(data);
        $scope.feedResult = 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.