【问题标题】:Reading data from JSON file in Angularjs从 Angularjs 中的 JSON 文件读取数据
【发布时间】:2014-10-15 20:59:05
【问题描述】:

嘿,我是 Angularjs 的新手。我正在尝试从 JSON 文件中读取数据,但它返回一个奇怪的输出。 这是我的 controller.js 文件

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

})

这是我的 services.js 文件

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;    
            })
           ]          
        }
   }
})

控制台输出是

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

请帮忙。

【问题讨论】:

    标签: javascript json html angularjs


    【解决方案1】:

    $http.get 返回一个 Promise,而您正在返回一个包含该 Promise 的数组。

    改为这样做:

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

    然后这样使用你的工厂:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多