最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular Service - Return http response - Stack Overflow

programmeradmin0浏览0评论

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.

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.

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.

//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);

        };
    })

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.

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.

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.

//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);

        };
    })
Share Improve this question asked Feb 16, 2015 at 15:26 MissCoder87MissCoder87 2,66910 gold badges49 silver badges82 bronze badges 4
  • I have better way to implement it. – micronyks Commented Feb 16, 2015 at 15:29
  • It will not work as you service doesn't return anything. – micronyks Commented Feb 16, 2015 at 15:32
  • you need to wait until promise is resolved var promise = SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login); promise.then(function(data){$scope.data = data}) – Pankaj Parkar Commented Feb 16, 2015 at 15:36
  • You can not return from an ajax call, it will return a promise which can be extended with .then – Michelangelo Commented Feb 16, 2015 at 15:37
Add a ment  | 

3 Answers 3

Reset to default 3

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

.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 $http function call, it returns Promise which you use in controller.

saveSubmitService Service method is returning promise and it can be resolved using .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

.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){ });
    )};
发布评论

评论列表(0)

  1. 暂无评论