在Angularjs中从JSON文件中读取数据 [英] Reading data from JSON file in Angularjs
本文介绍了在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 );
返回[
$ http.get('/ api / get.json')。then(function(msg){
返回msg.data;
})
]
}
}
})
控制台输出是
数据来自JSON:
[对象]
0:对象
长度:1
__proto__:数组[0
请帮忙。
解决方案
$ http.get 会返回一个承诺而你又回来了包含该承诺的数组。
请改为:
angular
.module('app.services',[])
.factory('Friend',function($ http){
return {
get:function(){
console.log(inside function);
返回$ http.get('/ api / get.json');
}
};
});
然后按照以下方式使用您的工厂:
.angular
.module('app.controllers',['app.services'])
.controller('yourCtrl',function($ scope,Friend) ){
Friend.get()。then(function(msg){
$ scope.msg = msg;
});
});
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";
})
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 is
DATA FROM JSON:
[Object]
0: Object
length: 1
__proto__: Array[0
Please help.
解决方案
$http.get returns a promise and you're returning 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 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屋!
查看全文