问题
I am trying to get a callback from the angular service but the callback function does not work.
Here is My controller code:-
$scope.uu = "hello" // this i just make for test
$scope.login = function(user){
//console.log(user)
AuthenticationService.Login(user.username,user.password).success(function(data){
console.log(data);
$scope.uu = data;
})
}
My service code is:-
mainApp.service('AuthenticationService',function($http,$cookieStore,$rootScope){
var service = {};
service.Login = function (username, password, callback) {
$http({
method: "POST",
//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'users/authenticate',
data: {email: username,password:password}
})
.success(callback);
};
return service;
});
Neither I get response in console. Neither the scope is changed. I have referred to this question but the answer is not working for me. $http POST response from service to controller
回答1:
If you are writing service your code should look like this :
mainApp.service('AuthenticationService',function($http,$cookieStore,$rootScope){
this.Login = function (username, password, callback) {
$http({
method: "POST",
//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'users/authenticate',
data: {email: username,password:password}
})
.success(callback);
};
});
Always remember service is just like prototype function
We should not return object in cas of service. Angular Instantiate the object and return automatically
来源:https://stackoverflow.com/questions/41425879/http-post-callback-not-working-angular-factory