我收到了运行时错误 cannot read property listArr of undefined
. 我需要在多个组件中重用相同的数组 . 那's why I' m使用全局数组
我添加了相关代码 . 请检查一下 .
Global.ts :
export class Global {
public static listArr: ObservableArray<ListItem> = new ObservableArray<ListItem>();
}
ts file:
Global.listArr.push(data.items.map(item => new ListItem(item.id, item.name, item.marks)));
html file:
<ListView [items]="Global.listArr" > </ListView>
3 回答
我可以告诉你最好不能直接在模板中引用全局变量,因为模板绑定到组件实例 . 您必须提供通过组件到模板的路径以获取要呈现的全局值 . 虽然创建服务是一个很好的选择,但您也可以在组件上创建一个getter并包装全局变量 .
见Working Demo
这个要点是:
我建议你去
Shared Services
. 保持服务中的全局数组将服务标记为app.module中的提供者i:emain module
.将其添加到
providers
NgModule
数组中 .现在你可以在 any Component 中使用它了
我选择服务的原因是它使用 Angular's Dependency Injection 并且它是拥有全局变量并在组件之间共享的最佳Angular方式 .
如果您希望组件在推送和弹出时自动通知阵列中的更改,您可以使用服务中的行为主题 . LINK - 问题2
您无法直接在模板中访问类静态属性 . 您需要创建属性的实例才能使用它 .
在这种特定情况下,在类中创建一个引用
Global.listArr
的实例 . 您可以使用此变量来推送数据并在模板中使用 . 其他组件也将保持最新状态 .Ts file:
Html:
链接到working demo .