代码之家  ›  专栏  ›  技术社区  ›  user9326447

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

  •  1
  • user9326447  · 技术社区  · 7 年前

    我正在尝试从控制器调用服务,这给了我以下错误。。 提供程序“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 回复  |  直到 7 年前
        1
  •  1
  •   Bimlendu Kumar    7 年前
    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
    });
    
        2
  •  0
  •   Estus Flask    7 年前

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

    如果要使用 喜欢 this.validateUser = ... 使用 service 而是服务。