5

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

        };
    })
4
  • I have better way to implement it. Commented Feb 16, 2015 at 15:29
  • It will not work as you service doesn't return anything. 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}) 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 Commented Feb 16, 2015 at 15:37

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That makes sense. The only thing i don't get is data is undefined on the controller
Make sure to access data inside then callback, not outside.
I am, your exact code falls over with data is not defined
Is data defined in success block: console.log(data)? You get in then block whatever you return from success.
oops, sorry there was a type in my code, it should be .then(function(data) {...}. Check updated code, I forgot data before.
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.