MissCoder87
MissCoder87

Reputation: 2669

Angular Service - Return http response

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

        };
    })

Upvotes: 5

Views: 14194

Answers (3)

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 3

micronyks
micronyks

Reputation: 55443

.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){ });
    )};

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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

Upvotes: 0

Related Questions