简体   繁体   English

异步数据获取和角度库

[英]async data fetching and angular library

"I have the following problem: I would like to fetch json from async rest call and use it in some existing directives from an Angular library (in my case angular-ui-tree and angular-charts). “我有以下问题:我想从异步rest调用中获取json,并在Angular库的某些现有指令中使用它(在我的情况下为angular-ui-tree和angular-charts)。

This is a simple example with angular-ui-tree for try to explain my problem . 这是一个带有angular-ui-tree的简单示例,试图解释我的问题。 The service: 服务:

var mod = angular.module("user.services");
mod.factory("userService", ["$http",  function ($http) {

    return {
        getUserMenu: function () {
        //call rest
            return $http.get('/user/menu').then(function (response) {
                    return response.data;
            });
        }
    };
}]);

The controller: 控制器:

var mod = angular.module("admin.controllers");
$scope.menu = [];
userService.getUserMenu().then(function(menuResp){
     $scope.menu = menuResp;
};
$scope.showbody = true;
$scope.selectedItem = {}; 
$scope.options = {};
...

Page (it's only a fragment): 页面(仅是一个片段):

<div ng-controller="MenuListCtrl">
<script type="text/ng-template" id="items_renderer.html">
   <div ui-tree-handle>... </div>
   <ol ui-tree-nodes="options" ng-model="item.items">
    <li ng-repeat="item in item.submenu" ui-tree-node ng-include="'items_renderer.html'"></li>
    </ol>
</script>
<div ui-tree="options">
<ol ui-tree-nodes ng-model="list" >
 <li ng-repeat="item in menu" ui-tree-node ng-include="'items_renderer.html'"></li>
</ol>
</div>

When I open my page the tree is correctly render but i have an error in console. 当我打开页面时,树已正确渲染,但控制台出现错误。 In Angular-ui case the error is "Cannot read property '0' of undefined". 在Angular-ui情况下,错误是“无法读取未定义的属性'0'”。 I think it's because when controller was been loading menu var wasn't set. 我认为这是因为在控制器加载菜单var时未设置。

Probably this way is wrong. 这种方式可能是错误的。 I think the solution is render the angular-ui-tree fragment after data loading. 我认为解决方案是在数据加载后呈现angular-ui-tree片段。 Something like this: 像这样:

var mod = angular.module("tnp.admin.controllers");
userService.getUserMenu().then(function(menuResp){
//render tree template with menuResp data or append in my fragment the angular-ui-tree directive with menuResp data
};

I have this problem with others libraries. 我在其他图书馆遇到这个问题。 The error is different but i think the base problem is the same. 错误是不同的,但我认为基本问题是相同的。 Someone can help my? 有人可以帮助我吗? How can I render my fragment this menu data? 如何呈现此菜单数据片段? Thanks!!! 谢谢!!!

I don't see why menu would need to be declared in your service. 我不明白为什么menu需要在您的服务中声明。 You should make sure that $scope.menu is set to an empty array in your controller before you call the service to populate it. 在调用服务以填充$scope.menu之前,应确保在其控制器$scope.menu设置为空数组。

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

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