I don't know how to make a service for a json file and call this service in my controller. I have one controller in my app,and so must remain.
2 Answers
Try to run this example via run code snippet blue button.
Basically, You need to declare that service, the require it via Angular.DI, lastly call the service method and wait for its result.
Hope it helps
angular
.module('test', [])
.constant('API' , 'https://jsonplaceholder.typicode.com')
.service('TestService', function(API, $http) {
this.getData = function() {
return $http
.get(API + '/photos')
.then(function(response) {
return response.data;
})
};
})
.controller('TestCtrl', function($scope, TestService) {
//But a Resolve is preferred
TestService
.getData()
.then(function(data) {
$scope.album = data;
})
;
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<div ng-repeat="photo in album">
<h3 ng-bind="photo.title"></h3>
<img ng-src="{{photo.thumbnailUrl}}" />
</div>
</article>
</section>
Comments
You have to call your service from your controller.
your service:
angular.module('YOURAPP')
.service("userAService", function ($http) {
this.promise= function () {
return $http.get('resources/json/data.json')
}
});
And then in your controller function:
mycontroller = function(userAService){
userAService.promise().then(
function(response){
//do what you want in your promise
// try console.log(response.data) to see if you get your data.
}
)
}
userAServiceandgetUserData?