http post callback not working angular factory

耗尽温柔 提交于 2019-12-13 08:26:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!