简体   繁体   English

angular js-获取json数据

[英]angular js - getting json data

I am trying to get data from json data so i write this: 我试图从json数据中获取数据,所以我这样写:

app.factory('data', function($resource) {
    return $resource('mock/plane_urls.json', {}, {
        getTreeData: { method: 'GET', isArray: false }
    })
})

and then using: 然后使用:

data.getTreeData.Carriers.Carrier;

Where Carriers is the first node in json file. 其中Carriers是json文件中的第一个节点。 but it doesnt work ;/ I got error 但这不起作用; /我得到了错误

Error: data.getTreeData.Carriers is undefined 错误:data.getTreeData.Carriers未定义

You are trying to reach into the Carriers object before it is fetched. 您正在尝试在提取Carriers之前到达Carriers对象。 Before the data comes back, Carriers is just an empty object. 在数据返回之前,载波只是一个空对象。

You could do something like $scope.carriers = data.getTreeData(); 您可以执行类似$scope.carriers = data.getTreeData(); and then in your view have an element with ng-repeat="carrier in carriers" 然后在您认为包含ng-repeat="carrier in carriers"的元素

The idea behind $resource is that you get an empty object, so the view renders nothing. $ resource背后的想法是,您得到一个空对象,因此视图不呈现任何内容。 When the request is complete, the empty object is replaced and the view is re-rendered with the data automatically. 请求完成后,将替换空对象,并自动使用数据重新渲染视图。

You could also use the $http service like so and provide a callback function that executes once the data is fetched. 您也可以像这样使用$ http服务,并提供一个回调函数,该函数在获取数据后立即执行。

$http.get('mock/plane_urls.json').then(function(data){
    carrier = data.Carriers.Carrier
});

BUT! 但! should break this into a service and a controller though. 应该将其分为服务和控制器。 Just have the service getTreeData return the promise object like so: return $http.get('mock/plane_urls.json'); 只需让服务getTreeData返回promise对象即可: return $http.get('mock/plane_urls.json'); and then in your controller call it with then() and provide the callbacks for success and error: 然后在您的控制器中使用then()进行调用,并提供成功和错误的回调:

getTreeData.then(
    function(data){
        carrier = data.Carriers.Carrier;
    }, 
    function(err){
        console.log("Error: " + err);
    });

You can use $scope.$watch to watch the value of the data.getTreeData. 您可以使用$ scope。$ watch来监视data.getTreeData的值。 When new data comes in, the callback will be called, then, you can get your data you want. 当输入新数据时,将调用回调,然后,您可以获取所需的数据。

http://docs.angularjs.org/api/ng .$rootScope.Scope http://docs.angularjs.org/api/ng。$ rootScope.Scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM