0

I started with AngularJS yesterday, so I'm sure I'm being extremely dumb on this question, but here we go.

This is my service.

angular.module('UserService', ['ngResource'])
    .factory('User', ['$resource', '$http', function($resource, $http){

    User = {};
    User.login = function (){
        var url = 'http://example.com/api/user/login';
        loginInfo = $http({
            method: 'POST',
            url: url,
            data: "user=user&pass=imagethereisahugepasshere",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(data){
            loginInfo = data;
        })
        return loginInfo;
    }


    return User;


}])

If I attach it to my controller and call console.log(User.login()), it returns me the promise instead the response (which is right, according to network Chrome tab).

What am I doing wrong?

Alex M.
  • 635
  • 1
  • 6
  • 19
  • 1
    Go through [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Satpal Jan 28 '15 at 16:42

2 Answers2

1

In your code:-

 return--> loginInfo =$http({
                method: 'POST',
                url: url,
                data: "user=user&pass=imagethereisahugepasshere",
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function(data){
                loginInfo = data;<-- doesn't come into picture
            })
    return loginInfo;<--$http service promise rather than local data variable

Obviously loginInfo is a $http service promise .

squiroid
  • 13,809
  • 6
  • 47
  • 67
1

Because it's an asynchronous request, it will not have completed when the function returns. That's why you have a success callback to do whatever needs to be done when the request actually completes.

Getting a promise back allows you to handle it in a different way - you can use .then() to do something after the promise is completed. But it's important to know that the function will return before it gets data back.

James Waddington
  • 2,894
  • 2
  • 15
  • 24
  • OK. What do you suggest, then? I guess I need to think another way, but I don't know how. – Alex M. Jan 28 '15 at 16:46
  • The simple answer is just do what you need to do in the success callback, or use the promise: loginInfo.then(function(data) {//dostuffhere});. It is important to have it in your mind that your code won't always flow straight through - functions will be invoked as data is returned. So you should bear that in mind when you structure the code. Angulars data binding helps a lot because it takes care of a lot for you. – James Waddington Jan 28 '15 at 16:50
  • I did it, and it worked. Now I must think on some way to integrate it on the flow that's in my head. Thanks. – Alex M. Jan 28 '15 at 16:59