Angularjs 在服务中使用$http时出现问题

Angularjs 在服务中使用$http时出现问题,angularjs,Angularjs,我有一个基本的数据服务,将在控制器之间使用。但是我在获取一些通过$http添加的数据时遇到了问题 服务: angular.module('core').service('FormService', ['$http', function($http) { var _this = this; _this.dropdownData = { contactTimes: ['Anytime','Morning','Afternoon','Evening'],

我有一个基本的数据服务,将在控制器之间使用。但是我在获取一些通过
$http
添加的数据时遇到了问题

服务:

angular.module('core').service('FormService', ['$http', function($http) {
    var _this = this;
    _this.dropdownData = {
        contactTimes: ['Anytime','Morning','Afternoon','Evening'],
        industries: {},
    };

    $http.get('/json').success(function(resp){
        _this.dropdownData.industries = resp.industries; 
    });
}]);
控制器:

angular.module('core').controller('SignupController', ['$scope', '$http', '$state', 'FormService', function($scope, $http, $state, FormService) {

    console.log(FormService.dropdownData); // Shows full object incl industries
    console.log(FormService.dropdownData.industries); // empty object {}

}]);

如何在我的控制器中获取
FormService.dropdownData.industries

假设您的数据确实存在,并且服务器没有问题,那么有很多可能的解决方案

还愿 使用routeProvider/ui路由解析 见:



您还可以编写一个函数,在应用程序开始运行时初始化服务。归根结底,这是关于使用承诺等待数据加载。如果您以前从未听说过承诺,请先告诉自己。

假设您的数据确实存在,并且服务器没有问题,那么有很多可能的解决方案

还愿 使用routeProvider/ui路由解析 见:



您还可以编写一个函数,在应用程序开始运行时初始化服务。归根结底,这是关于使用承诺等待数据加载。如果您以前从未听说过承诺,请先告诉自己。

创建一个如下所示的服务

appService.factory('Service', function ($http) {
        return {
            getIndustries: function () {
                return $http.get('/json').then(function (response) {
                    return response.data;
                });
            }
        }
    });
_this.getindustries = function (callback) {
        return $http.get('/json').success(function(resp){
            _this.dropdownData.industries = resp.industries; 
            callback(_this.dropdownData)
      });
    };
呼叫控制器

appCtrl.controller('personalMsgCtrl', ['$scope', 'Service', function ($scope, Service) {
    $scope.Industries = Service.getIndustries();
}]);

希望这将有助于创建如下服务

appService.factory('Service', function ($http) {
        return {
            getIndustries: function () {
                return $http.get('/json').then(function (response) {
                    return response.data;
                });
            }
        }
    });
_this.getindustries = function (callback) {
        return $http.get('/json').success(function(resp){
            _this.dropdownData.industries = resp.industries; 
            callback(_this.dropdownData)
      });
    };
呼叫控制器

appCtrl.controller('personalMsgCtrl', ['$scope', 'Service', function ($scope, Service) {
    $scope.Industries = Service.getIndustries();
}]);

希望这对您有所帮助,因为您的控制台日志显示了正确的对象,表明您的服务运行正常。你在这里只犯了一个小错误。您需要访问退货承诺中的
数据
属性

angular.module('core').service('FormService', ['$http', function($http) {
  var _this = this;
  _this.dropdownData = {
     contactTimes: ['Anytime','Morning','Afternoon','Evening'],
     industries: {},
 };

 $http.get('/json').success(function(resp){
    //note that this is resp.data.industries, NOT resp.industries
    _this.dropdownData.industries = resp.data.industries; 
   });
 }]);

假设您的控制台日志显示了正确的对象,则表明您的服务运行正常。你在这里只犯了一个小错误。您需要访问退货承诺中的
数据
属性

angular.module('core').service('FormService', ['$http', function($http) {
  var _this = this;
  _this.dropdownData = {
     contactTimes: ['Anytime','Morning','Afternoon','Evening'],
     industries: {},
 };

 $http.get('/json').success(function(resp){
    //note that this is resp.data.industries, NOT resp.industries
    _this.dropdownData.industries = resp.data.industries; 
   });
 }]);

industries对象将在稍后$http调用返回时填充。同时,您仍然可以绑定到视图中的引用,因为您使用angular.copy保留了引用。当$http调用返回时,视图将自动更新

允许服务用户在$http调用返回时处理事件也是一个好主意。您可以通过将$promise对象保存为industries的属性来实现这一点:

angular.module('core').service('FormService', ['$http', function($http) {
    var _this = this;
    _this.dropdownData = {
        contactTimes: ['Anytime','Morning','Afternoon','Evening'],
        industries: {},
    };

    _this.dropdownData.industries.$promise = $http.get('/json').then(function(resp){
               // when the ansyc call returns, populate the object, 
               // but preserve the reference
               angular.copy( resp.data.industries, _this.dropdownData.industries); 
               return _this.dropdownData.industries;
           });


}]);
控制器

    app.controller('ctrl', function($scope, FormService){
              // you can bind this to the view, even though the $http call has not returned yet
              // the view will update automatically since the reference was preserved
              $scope.dropdownData = FormService.dropdownData;

              // alternatively, you can hook into the $http call back through the $promise
              FormService.dropdownData.industries.$promise.success(function(industries) {
                     console.log(industries);
              });
    });

industries对象将在稍后$http调用返回时填充。同时,您仍然可以绑定到视图中的引用,因为您使用angular.copy保留了引用。当$http调用返回时,视图将自动更新

允许服务用户在$http调用返回时处理事件也是一个好主意。您可以通过将$promise对象保存为industries的属性来实现这一点:

angular.module('core').service('FormService', ['$http', function($http) {
    var _this = this;
    _this.dropdownData = {
        contactTimes: ['Anytime','Morning','Afternoon','Evening'],
        industries: {},
    };

    _this.dropdownData.industries.$promise = $http.get('/json').then(function(resp){
               // when the ansyc call returns, populate the object, 
               // but preserve the reference
               angular.copy( resp.data.industries, _this.dropdownData.industries); 
               return _this.dropdownData.industries;
           });


}]);
控制器

    app.controller('ctrl', function($scope, FormService){
              // you can bind this to the view, even though the $http call has not returned yet
              // the view will update automatically since the reference was preserved
              $scope.dropdownData = FormService.dropdownData;

              // alternatively, you can hook into the $http call back through the $promise
              FormService.dropdownData.industries.$promise.success(function(industries) {
                     console.log(industries);
              });
    });

向服务中添加一个方法并使用$Http.get,如下所示

appService.factory('Service', function ($http) {
        return {
            getIndustries: function () {
                return $http.get('/json').then(function (response) {
                    return response.data;
                });
            }
        }
    });
_this.getindustries = function (callback) {
        return $http.get('/json').success(function(resp){
            _this.dropdownData.industries = resp.industries; 
            callback(_this.dropdownData)
      });
    };
在您的控制器中,您需要如下访问它

 angular.module('core').controller('myController', ['$scope', 'FormService', function ($scope, FormService) {
   FormService.getDropdownData(function (dropdownData) {
       console.log(dropdownData); // Shows full object incl industries
       console.log(dropdownData.industries); // object {}
   });

})

向您的服务添加一个方法并使用$Http.get,如下所示

appService.factory('Service', function ($http) {
        return {
            getIndustries: function () {
                return $http.get('/json').then(function (response) {
                    return response.data;
                });
            }
        }
    });
_this.getindustries = function (callback) {
        return $http.get('/json').success(function(resp){
            _this.dropdownData.industries = resp.industries; 
            callback(_this.dropdownData)
      });
    };
在您的控制器中,您需要如下访问它

 angular.module('core').controller('myController', ['$scope', 'FormService', function ($scope, FormService) {
   FormService.getDropdownData(function (dropdownData) {
       console.log(dropdownData); // Shows full object incl industries
       console.log(dropdownData.industries); // object {}
   });

})

你能至少粘贴该对象的结构吗?或者plunkr示例会有帮助吗?你能至少粘贴该对象的结构吗?或者plunkr示例会有帮助吗?请注意,Nitin将原始服务转换为一个工厂,其行为略有不同。是的,它的工作原理略有不同,请看这篇文章注意,Nitin将原始服务转化为一个工厂,其行为稍有不同。是的,它的工作原理稍有不同,请看这篇文章谢谢,我理解这是一个多么大的承诺,但我觉得奇怪的是,
FormService.dropdownData.industries
返回了一个空obj,虽然
FormService.dropdownData
返回了完整的对象,包括
industries
的所有值,但我知道这是一个多么大的承诺,但是
FormService.dropdownData.industries
返回了一个空的对象,这让我感到奇怪,虽然
FormService.dropdownData
返回了完整的对象,包括
行业的所有值
谢谢,但我觉得这是最优雅和可重用的答案。此外,您还可以将http调用移动到单独的服务,使用您的服务访问http。这将使代码更易于维护。下面给出了ajaxcalls的示例。(function(angular){angular.module('onboardingApp').service('ajaxService',function($http){var self=this;self.get=function(options){options.type='get';if(options.blockUI==未定义){options.blockUI=true;}返回$.ajax(options);};self.post=函数(options){options.type='post';if(options.blockUI==未定义){options.blockUI=true;}返回$.ajax(options);};};};(角度);谢谢,我觉得这是最优雅和可重用的答案。另外,您可以将http调用移动到单独的服务,使用您的服务访问http。这将使代码更易于维护。下面给出了ajaxcalls的示例。(function(angular){angular.module('onboardingApp')。service('ajaxService',function($http){var self=this;self.get=function(options){options.type='get';if(options.blockUI==undefined){options.blockUI=true;}返回$.ajax(options);};self.post=function(options){options.type='post';if(options.blockUI==未定义){options.blockUI=true;}返回$.ajax(选项);};};})(角度);