【问题标题】:return a value from $get factory method when calling service from controller in AngularJs从 AngularJs 中的控制器调用服务时,从 $get 工厂方法返回一个值
【发布时间】:2018-02-28 17:29:01
【问题描述】:

我试图从控制器调用服务,这给了我以下错误.. Provider '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];
                });
        }
});

【问题讨论】:

    标签: angularjs service controller


    【解决方案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
    });
    

    【讨论】:

      【解决方案2】:

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

      如果您想像this.validateUser = ... 一样使用this,请改用service 服务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        相关资源
        最近更新 更多