Search code examples
javascriptangularjsjsonajaxangularjs-service

How to correctly return my data from AJAX call (AngularJS)


I have a view that calls this function below which makes an AJAX call to our API - this for some reason always returns 'undefined' when I view this in the AngularScope using the Firefox DOM inspection tool.

If I check the Network tab I can see this URL has been called and can see the JSON which I expect, I then want to return the data.words JSON data but this is always returning undefined? If I remove the AJAX call and just leave in the last return with the 'static' and 'words' in this works as expected, so it is clear to me something about the returning in the AJAX success call doesn't seem to be right... any ideas??

// within a AngularJS service file

this.getAccSignoffWords = function() {
    var url = ApiService.getDomain() + 'account/signoff';
    $http({
        method : 'GET',
        url : url
    }).success(function(data) {
        if (data.success) {
            return data.words; // I want to return this JSON to the scope
        }
    }).error(function(data) {
        throw "Failed to get sign-off words";
    })['finally'](function(data) {

    });

    // return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words
}

Solution

  • thing is when you are sending the http request, it take some time to process and send data back to your javascript code. but since the javascript is asynchronous, it doesn't wait until response return. so either you can return the whole http request like Umakanta Behera suggested or you can use a callback function to wait unit the response come back.

    this.getAccSignoffWords = function(callback) {
        var url = ApiService.getDomain() + 'account/signoff';
        $http({
            method : 'GET',
            url : url
        }).success(function(data) {
            if (data.success) {
                callback() data.words
            }
        }).error(function(data) {
            throw "Failed to get sign-off words";
        })['finally'](function(data) {
    
        });
    }
    

    call this function like this

    this.getAccSignoffWords(function(data){
         console.log(data) // your http response 
    })