在 Angularjs 中从 JSON 文件中读取数据 [英] Reading data from JSON file in Angularjs

查看:29
本文介绍了在 Angularjs 中从 JSON 文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hai i am new in Angularjs. I am trying to read data from JSON file, But it returns a 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";       

})

这是我的 services.js 文件

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

控制台输出是

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

请帮忙.

推荐答案

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

$http.get returns a promise and you're returning an array containing that promise.

改为这样做:

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

然后以这种方式使用您的工厂:

Then use your factory this way:

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

这篇关于在 Angularjs 中从 JSON 文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆