在角度http成功响应之前执行的函数

时间:2016-08-04 08:39:03

标签: angularjs angularjs-directive angular-http

我试图使用指令控制器来点击Web服务,我点击了post方法并获得了响应,但是我期望的值变为空,因为所有在成功响应之前编译。 这是指令

中的控制器
controller: ['$scope', '$http', 'popupService','SessionUtils', function($scope, $http, popupService,SessionUtils) {
                $scope.responseValue = "";
                  $scope.sendCSVFile = function(link, fileData) {
                    $scope.seriveResponse = $http({
                      method: "POST",
                      url: link,
                      data: fileData,
                      headers: {
                        'Content-Type': undefined
                      }
                    }).success(function(response) {
                        if(response.status == "FAILURE"){
                            popupService.showErrMsg(response.message);
                            return false;
                        }
                        else {
                            $scope.responseValue = response;
                            //SessionUtils.updateResponse(response);
                            var success = "File Uploaded Successfully";
                            popupService.showSuccessMsg(success);
                            return response;
                        }
                        return $scope.responseValue = response;
                    });

                    });

我从指令链接函数调用控制器,如

var res = scope.sendCSVFile(attrs.getUrlModel, formData); 
scope.gridUpdate(res);

res返回undefined,但是在我绑定res之后我得到了响应。如何获得有希望的响应并在执行后执行该功能。!

1 个答案:

答案 0 :(得分:0)

您可以获得承诺,而不是标准数据,ajax是异步调用,因此将代码更改为:

$scope.sendCSVFile = function(link, fileData) {
                return $http({ //return promise object
                  method: "POST",
                  url: link,
                  data: fileData,
                  headers: {
                    'Content-Type': undefined
                  }
                }).success(function(response) {
                    if(response.status == "FAILURE"){
                        popupService.showErrMsg(response.message);
                        return false;
                    }
                    else {
                        $scope.responseValue = response;
                        //SessionUtils.updateResponse(response);
                        var success = "File Uploaded Successfully";
                        popupService.showSuccessMsg(success);
                        return response;
                    }
                    return $scope.responseValue = response;
                });

                });

用法:

$scope.sendCSVFile(attrs.getUrlModel, formData).then(function(response){

    //here ajax is completed and in response variable You have raturn from success callback
    if (response)
    scope.gridUpdate(response);
});