在AngularJs中从控制器调用服务时,从$ get factory方法返回一个值

时间:2018-02-28 08:51:52

标签: angularjs service controller

我试图从控制器调用服务,这给我以下错误.. 提供商' loginService'必须从$ get factory方法返回一个值。

下面是我的代码。我做错了什么。

控制器代码

 app.controller('loginController', ['$scope', '$http', 'loginService', function ($scope, $http, loginService) {
        $scope.checkdata = function () {
            var userName = $scope.username;
            var password = $scope.password;

            //Call the login service
            loginService.validateUser(userName, password);
            alert(response.data);
        }
    }])

服务代码

app.factory('loginService', function ($http) {

            this.validateUser = function (userName, password) {


                var userData = new Object();
                userData.userName = userName;//Data.username;
                userData.password = password;//Data.password;
                return $http({
                    url: "http://localhost:53181/api/User",
                    dataType: 'json',
                    method: 'POST',
                    data: userData,
                    headers: {
                        "Content-Type": "application/json"
                    }
                }).then(function (response) {
                    alert(response);
                    if (response.data && response.data.data && response.data.data.length == 1)
                        return response.data.data[0];
                });
        }
});

2 个答案:

答案 0 :(得分:1)

Create service funtcion like this:
yourAPICallingFuntion: function() {
                var url = "your url";
                var deferred = $q.defer();
                $http.get(url, {
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                }).then(function(data) {
                    deferred.resolve(data.data);
                }, function(error) {
                    deferred.reject(error);
                });
                return deferred.promise;
            }
In Controller Call like this:
loginService.yourAPICallingFuntion().then(function(data){
//Now this will give you response in form of data
//you can this data according to your requirement
});

答案 1 :(得分:0)

factory服务预计会从工厂函数返回一个值。它没有this上下文(它是windowundefined)。

如果您想使用this之类的this.validateUser = ...,请改用service服务。