Reputation: 430
I want to create a service that get a json
data.
controller :
angular.module('app')
.controller('serviceCtrl',['$scope', 'Services', function($scope,Services) {
$scope.title="services";
$scope.services = Services.get();
}]);
factory service :
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>
but i am getting an error ReferenceError: $http is not defined
is it right the way i create the factory ?
Upvotes: 1
Views: 1363
Reputation: 9123
$http is part of angular and you need to inject it into your factory before you can use it. Moreover you do not want to return a promise, but an object which has the functionality you need.
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
};
}
Afterwards you can use this service in your controller.
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;
});
}
}
Note that it is better to resolve promises before you actually load the state.
Upvotes: 1