0

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.

3
  • What error do you get ? Commented Sep 29, 2016 at 14:33
  • I don't have an error, I don't view the json file content on my screen. Commented Sep 29, 2016 at 14:35
  • Where do you call userAService and getUserData ? Commented Sep 29, 2016 at 14:36

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.
         }
     )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.