2016-12-05 76 views
1

我想创建一个获取json数据的服务。使用服务获取json数据

控制器:

angular.module('app') 
    .controller('serviceCtrl',['$scope', 'Services', function($scope,Services) { 
     $scope.title="services"; 
     $scope.services = Services.get(); 
}]); 

工厂服务:

angular.module('app') 
     .factory('Services', function(){ 
      return $http.get('/api/services.json').then(function(response){ 
       return response.data; 
      }) 
     }); 

service.html:

<div ng-repeat="service in Services"> 
    <div class=" thumbnail-services col-xl-3 col-lg-4 col-md-4 col-sm-6 col-xs-6"> 
     <figure class="figure"> 
      <img src="http://placehold.it/350x350" class="figure-img img-fluid rounded" alt="{{Services.name}}"> 
      <figcaption class="figure-caption"> 
      <a href=""> 
       <h3>{{Services.name}}</h3> 
      </a> 
      </figcaption> 
     </figure> 
    </div> 
</div> 

但我得到一个错误ReferenceError: $http is not defined

是我创建工厂的方式吗?

回答

1

$ http是角度的一部分,你需要注入到你的工厂,然后才能使用它。此外,你不想要返回一个承诺,而是一个具有你需要的功能的对象。

angular 
    .module('app') 
    .factory('Services', myService); 

    myService.$inject = ['$http']; 

    function myService($http){ 
     function getJson() { 
      return $http.get('/api/services.json').then(function(response){ 
       return response.data; 
      }) 
     } 

     return { 
      getJson: getJson 
     }; 
    } 

之后,您可以在您的控制器中使用此服务。

angular 
    .module('app') 
    .controller('serviceCtrl', serviceCtrl); 

    serviceCtrl.$inject = ['$scope', 'Services']; 

    function serviceCtrl($scope,Services){ 
     var vm = this; 
     this.json = {} 

     activate(); 

     function activate(){ 
      Services.getJson().then(function(response){ 
       vm.json = response; 
      }); 
     } 
    } 

请注意,最好在实际加载状态之前解决承诺。

+0

但它仍然给我输出angular.js:14110 TypeError:Services.get不是一个函数。 – GerryofTrivia

+1

@vandi这是因为他将它命名为'.getJson()'而不是'.get()'。不要只复制粘贴代码,尝试阅读和理解概念。 – devqon

相关问题