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

问题描述 投票:1回答:2

我试图从控制器调用服务,这给我下面的错误..提供者'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];
                });
        }
});
angularjs service controller
2个回答
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
});

0
投票

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

如果你想使用像this这样的this.validateUser = ...,请改用service服务。

© www.soinside.com 2019 - 2024. All rights reserved.