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



我试图从控制器调用服务,这给了我以下错误。提供程序"loginService"必须从工厂方法返回$get值。

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

控制器代码

 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];
                });
        }
});
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
});

factory服务应从工厂函数返回一个值。它没有this上下文(要么是window,要么是undefined(。

如果要使用this,如 this.validateUser = ... ,请改用service服务。

最新更新