Angular:如何在$ http请求成功之后推迟返回

时间:2015-07-10 03:08:21

标签: javascript arrays angularjs http

在我的主模块中,我希望创建一个解析json文件并将内容推送到数组的服务,之后我希望服务能够返回数组,以便任何控制器都可以轻松访问它。问题是函数在$ http请求完成之前运行,所以它总是返回一个空数组

var logoPath = Directory.GetFiles(Server.MapPath("~/Logo/")).OrderByDescending(f => File.GetCreationTime(f)).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(logoPath))
{
    payroll_company.comp_logo = Path.GetFileName(logoPath);
}

1 个答案:

答案 0 :(得分:4)

使用承诺,如:

dashModule.factory('dataFetchService', function($http) {
    var myReq = function() {
        return $http.get('../data/emails.json').then(function(response){
            return response.data;
        });
    };
    return { myReq: myReq };
});

function getMyReq($scope, dataFetchService) {
    var myReqPromise = dataFetchService. myReq();
    myReqPromise.then(function(result) {        
        console.log(result);
    });
}