0

I have an angularjs factory to get data via $http.get():

'use strict';
app.factory('apiService', ['$http', function ($http) {
    var apiService = {};
    apiService.urlBase = 'http://localhost:1337/api/';
    apiService.get = function (urlExtension) {
        $http({
            method: 'GET',
            url: apiService.urlBase + urlExtension
        }).then(function successCallback(response) {
            return response.data;
        }, function errorCallback(response) {
            console.log(response);
        });
    }

    return apiService;
}]);

The problem is, that it always returns undefined when i call the method apiService.get(); in a Controller. When I log the response data in the factory, it display the right data. The apiService.urlBase variable is always filled in my controller.

Do you guys have any suggestions or am I doing something wrong? Maybe it's a syntax error.

2 Answers 2

1

You are not returning the promise that is returned by $http. Add return before $http

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

1 Comment

yeah okay, this kind of works, but now i get a $$state object, do you have any suggestions on how to handle that?
0

Okay I solved the problem. I just passed a callback function via parameter for my get() function.

'use strict';
app.factory('apiService', ['$http', function ($http) {
    var apiService = {};
    apiService.urlBase = 'http://localhost:1337/api/';
    apiService.get = function (urlExtension, callback) {
        var data = {};

        $http({
            method: 'GET',
            url: apiService.urlBase + urlExtension
        }).then(function successCallback(response) {
            data = response.data;
            callback(data);
        }, function errorCallback(response) {
            console.log(response);
        });

        return data;
    }

    return apiService;
}]);

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.