Question

I am doing stubbed development using angularjs. My stubs are JSON files on the server. So, I am making $http calls within the "stub" function to get the stubs. However as $http is asynchronous, the whenGET returns empty data all the time (it does not wait for http to complete). I looked into current questions on this subject. They provide approach to assign the return value of http call to a scope data model. I want to return the data after the http request is complete. Below is the code.

stubbedOstnApp.run(['$httpBackend','$http',function($httpBackend, $http){
    var tempData;
    var get = function (){
        return $http.get('../test/data/program-categories.json').then(function(data){
            tempData = data.data;
            console.log(tempData);
            return tempData;
        })
    };
    get();
    console.log(tempData);

    $httpBackend.whenGET('lookup/program-categories').respond(tempData);
    $httpBackend.whenGET(/^views\//).passThrough();
    $httpBackend.whenGET(/^\.\.\/test\/data\//).passThrough();
}]);

Basically, I want the line whenGET to wait until the tempData is populated. The tempData inside the get function is logged in the console after the whenGET method is run.

Était-ce utile?

La solution

You should have the tempData populated on the success callback you provide to $http.get

Try it this way:

 var get = function (){
    return $http.get('../test/data/program-categories.json').then(function(data){
        tempData = data.data;
        $httpBackend.whenGET('lookup/program-categories').respond(tempData);            
        console.log(tempData);
        return tempData;
    })
};
get();
console.log(tempData);

Autres conseils

To do this, you should use promises: https://docs.angularjs.org/api/ng/service/$q

Excellent explanation of promises here: Processing $http response in service

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top