0

Created factory that will return json data and calling it from controller, but it is coming empty. don't know where I made mistake. no console error and in network json is also loading.

    'use strict';
var app = angular.module('angularJson', ['ngResource']);

    app.factory('loadJsonService', ['$resource', function ($resource) {
        return {
            getData: function () {
                return $resource('json/productDetails.json');
            }
        };
    }])

  app.controller('angularJsonCtrl',['$scope', 'loadJsonService',function($scope, loadJsonService){

    $scope.loadProducts = function(noOfData){
        $scope.productDetails = [];
        $scope.productDetails = loadJsonService.getData().query();
    }

  }]);
2
  • 1
    Your request is async. There's nothing to return because it hasn't finished yet. You need to use promises. Commented Jul 2, 2016 at 7:37
  • You need to take a look at ngResource Doc. Commented Jul 2, 2016 at 7:38

3 Answers 3

3

You have to put wait till request gets completed & there after you need to use .$promise.then over $resource.query function call. So that you could put function which will get call on success of API call.

loadJsonService.getData().query().$promise.then(function(res){ //success function
   $scope.productDetails = res;
}, function(error){ //error function
   console.log(error);
})
Sign up to request clarification or add additional context in comments.

4 Comments

What is the utility of .$promise ? I always do .then() directly.
@sylvain1264 as far as I know, $promise return original server interaction promise.. If you directly .then over it, It might get resolved before data returned from server
Thanks @PankajParkar
@ManojGupta Glad to help you, Thanks ;)
0

You must in getData function set $http request like this

$http.jsonp("json/productDetails.json")
        .success(function(response) {
          callback(response);
        });

2 Comments

may be use $http instead $resourse?
no man.. $resource is much matured & efficient than $http service,$resource play good with API calls
0

Try built in query method. If you want to write your own get method do the following,

{
   method: 'GET',
   params: {
   key: value
},
isArray: true,
cache: true // if you want to cache
}

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.