如何在angularJs中返回$ http的承诺

时间:2016-07-21 15:28:10

标签: angularjs angular-promise

我是AngularJS的新手。如何返回" response.data"的响应?作为典型的功能? 因为$http生成了一个promise,当函数完成时它不会返回服务器响应。

在我的控制器中我有:

this.message2 = function() {                 
    $http({
        url : 'dataset_of_model',
        method : "POST",
        data : {
            'experiment' : 'rcp85',
            'model' : 'HadGEM2-ES',
            'frequency' : 'day'
        }
    }).then(function(response) {
        console.log('qui');
        console.log(response.data);                               
        return response.data;
    }, function(response) {
        //fail case
        console.log(response);
        console.log(fallito);
        return  response;
    });
};

如果我这样做:

this.message2 = function() {

    var = temp;

    $http({
        url : 'dataset_of_model',
        method : 'POST',
        data : {
            'experiment' : 'rcp85',
            'model' : 'HadGEM2-ES',
            'frequency' : 'day'
        }
    }).then(function(response) {
        console.log('qui');
        console.log(response.data);                                  
        temp = response.data;
    }, function(response) {
        //fail case
        console.log(response);
        console.log(fallito);
        return response;
    });

    return temp;            
}; 

返回temp没有数据,因为它在数据之前返回,即使我在返回前等待10秒。

如何以同步方式返回数据?

谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个。

this.getResults = function(){
    return $http.get(url).then(function(res){
        //Resquest successs
    }, function(err){
        //Resquest fail
    });
}

然后

MyFooService.getResults().then(...);

答案 1 :(得分:-1)

我不确定为什么会这样做?您仍然可以在第一个选项中返回response.data。您还应该在$ http之前添加return(这样您将返回promise)。但是,您希望与响应同步的任何内容都必须位于.then块中。例如,如果您想获得所有得分的响应,然后将该数字添加到某个变量,您必须将该功能放在.then块中,然后在结尾处返回response.data。块。

这样,then块内执行的函数是同步的。

你不能保证在then块之外执行的函数,除非你想用$ timeout(停止2秒,然后执行返回temp)来破解它,我不推荐。