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?
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.