Reading data from JSON file in Angularjs

Hi, I'm new to Angularjs. I am trying to read data from a JSON file, but it is returning strange output. Here is my controller.js file

angular
.module('app')
.controller('homeCtrl',function($scope,Friend){
      $scope.friends=Friend.get();
      console.log("DATA FROM JSON:",$scope.friends);
      $scope.title="Home";       

})

      

Here is my services.js file

angular
.module('app')
.factory('Friend',function($http){

   return {
    get:function(){

            console.log("inside function");
            return [


            $http.get('/api/get.json').then(function(msg){

                return msg.data;    
            })
           ]          
        }
   }
})

      

console output

DATA FROM JSON: 
[Object]
0: Object
length: 1
__proto__: Array[0

      

Please, help.

+3


source to share


1 answer


$ http.get returns a promise and you return an array containing that promise.

Do this instead:

angular
.module('app.services', [])
.factory('Friend', function ($http) {
    return {
        get: function () {
            console.log("inside function");
            return $http.get('/api/get.json');
        }
    };
});

      



Then use the factory like this:

.angular
.module('app.controllers', ['app.services'])
.controller('yourCtrl', function ($scope, Friend) {
    Friend.get().then(function (msg) {
        $scope.msg = msg;
    });
});

      

+6


source







All Articles