javascript Angular 服务 - 返回 http 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28544750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:09:03  来源:igfitidea点击:

Angular Service - Return http response

javascriptangularjs

提问by TMB87

I'm trying to build an angular service I can reuse for doing my http requests etc. This all works when it's not in a service.

我正在尝试构建一个 angular 服务,我可以重用它来处理我的 http 请求等。当它不在服务中时,这一切都有效。

The following code works and does the login, but the log of $scope.data is always undefined. If i put a log in on the success before I return data it returns the data, but not back to the controller which is what i'm really looking to do.

以下代码有效并进行登录,但 $scope.data 的日志始终未定义。如果我在返回数据之前登录成功,它会返回数据,但不会返回控制器,这正是我真正想要做的。

Just for clarification, I want to be able to access the json data returned from the server as 'data' in the success in my controller.

为了澄清起见,我希望能够在我的控制器中成功访问从服务器返回的 json 数据作为“数据”。

//App.js

//App.js

.service('SaveSubmitService', function ($http, $log) {
    this.addItem = function(url, options){
        var xsrf = $.param({
            Username: options.Username,
            Password: options.Password
    });

    $http({
        method: 'POST',
        url: url,
        data: xsrf,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).success(function(data, status, headers, config) {
            return data;

    }).
        error(function(data, status, headers, config) {
            console.log(data);
            return false;


   });
    }

})

Controller:

控制器:

.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
        if (localStorage.getItem("SessionKey")) {
            $location.path('home');
        }
        $scope.login = {};
        $scope.doLogin = function doLogin() {

           $scope.data = SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
           $log.info($scope.data);

        };
    })

采纳答案by dfsq

First of all make SaveSubmitServicereturn promise object. Then use its API to provide a callback to be executed once data is loaded:

首先 make SaveSubmitServicereturn promise object。然后使用它的 API 提供一个回调以在数据加载后执行:

.service('SaveSubmitService', function ($http, $log) {
    this.addItem = function (url, options) {

        var xsrf = $.param({
            Username: options.Username,
            Password: options.Password
        });

        return $http({
            method: 'POST',
            url: url,
            data: xsrf,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
        .then(function(response) {
            return response.data;
        })
        .catch(function(error) {
            $log.error('ERROR:', error);
            throw error;
        });
    }
});

And the you will use it like this in controller:

您将在控制器中像这样使用它:

$scope.doLogin = function doLogin() {
    SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login).then(function(data) {
        $scope.data = data;
        $log.info($scope.data);
    });
};

Note, how you return result of $httpfunction call, it returns Promise which you use in controller.

请注意,如何返回$http函数调用的结果,它会返回您在控制器中使用的 Promise。

回答by Pankaj Parkar

saveSubmitServiceService method is returning promise and it can be resolved using .then(function())

saveSubmitService服务方法返回承诺,可以使用解决 .then(function())

Your controller code will look like below.

您的控制器代码如下所示。

CODE

代码

$scope.doLogin = function doLogin() {
    var promise = saveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
    promise.then(function(data) {
        $scope.data = data
    });
};

Thanks

谢谢

回答by micronyks

.factory('SaveSubmitService', function ($http, $log) {
    return{
    getData:function(url,xsrf)
    {
           $http({
                  method: 'POST',
                  url: url,
                  data: xsrf,
                  headers: {
                 'Content-Type': 'application/x-www-form-urlencoded'
                 }
          }).success(function(data, status, headers, config) {
               return data;

          }).
             error(function(data, status, headers, config) {
             console.log(data);
             return false;


         });
    }
   }

})


.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
        if (localStorage.getItem("SessionKey")) {
            $location.path('home');
        }
        $scope.login = {};
        $scope.doLogin = function doLogin() {

           $scope.data = SaveSubmitService.addItem(, );
           $log.info($scope.data);

        };

               SaveSubmitService.getData('http://*****/Services/Account.asmx/Login',$scope.login).success(function(data,status){
                 $scope.data
                 }).error(function(data,status){ });
    )};