1

我正在使用 angularjs 进行存根开发。我的存根是服务器上的 JSON 文件。所以,我在“存根”函数中调用 $http 来获取存根。然而,由于 $http 是异步的,whenGET 总是返回空数据(它不等待 http 完成)。我调查了有关此主题的当前问题。它们提供了将 http 调用的返回值分配给范围数据模型的方法。我想在http请求完成后返回数据。下面是代码。

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();
}]);

基本上,我希望行 whenGET 等到填充 tempData 。get 函数中的 tempData 在 whenGET 方法运行后记录在控制台中。

4

2 回答 2

1

您应该在提供给 $http.get 的成功回调中填充 tempData

试试这种方式:

 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);
于 2014-04-25T19:26:25.253 回答
0

为此,您应该使用承诺:https ://docs.angularjs.org/api/ng/service/$q

此处对 promise 的出色解释:Processing $http response in service

于 2014-04-25T19:14:32.273 回答