如何在构造函数之前保持组件的生命周期直到构造函数中的函数没有完成?

时间:2017-07-31 06:58:06

标签: angular

我正在开发angular2应用程序。

我有一个显示菜单的组件。在这个组件中,我有一个菜单项列表(数组),在构造函数中,我调用api来获取菜单项的权限为true / false。在循环通过menuList数组的HTML文件中打印它并使用权限对象编译每个menuList项。如果有权限,那么它将显示否则没有。

我收到错误,因为api需要时间来返回数据,但是在返回响应之前构建了html。这就是为什么我希望在组件初始化之后首先获得api的响应。

1 个答案:

答案 0 :(得分:1)

  

在循环通过menuList数组的HTML文件中打印它   我假设你正在使用function aggregate (array, predicate, value, reducer) { // group values by predicate var groups = array.reduce(function (groups, item) { if (item[predicate] in groups) { groups[item[predicate]].push(item[value]) } else { groups[item[predicate]] = [item[value]] } return groups }, {}) // aggregate each group of values by reducer return Object.keys(groups).map(function (group) { var summary = {} summary[predicate] = group summary[value] = groups[group].reduce(reducer, 0) return summary }) } // input array var arr = [{ type: 'kitchen appliance', quantity: 2 }, { type: 'home entertainment', quantity: 2 }, { type: 'home entertainment', quantity: 3 }, { type: 'batteries & lightings', quantity: 2 }, { type: 'home entertainment', quantity: 2 }, { type: 'home appliance', quantity: 5 }, { type: 'kitchen appliance', quantity: 4 }, { type: 'kitchen appliance', quantity: 5 }, { type: 'kitchen appliance', quantity: 3 }, { type: 'kitchen appliance', quantity: 4 }, { type: 'kitchen appliance', quantity: 1 }, { type: 'home entertainment', quantity: 1 }, { type: 'home appliance', quantity: 5 }, { type: 'batteries & lightings', quantity: 2 }, { type: 'kitchen appliance', quantity: 2 }, { type: 'home appliance', quantity: 2 }] // output array var sums = aggregate(arr, 'type', 'quantity', function (a, b) { return a + b }) // formatting var output = sums.map(function (item) { return item.type + ' ' + item.quantity }) // string output console.log(output.join('\n'))和这样的结构来显示项目:

ngFor

在这种情况下,最好的方法是不用<menu-item *ngFor="let item of menuItems"..> 填充值,直到从服务器获得响应。这些方面的东西:

menuItems