【问题标题】:cannot read property global array of undefined in nativescript angular2无法读取 nativescript angular2 中未定义的属性全局数组
【发布时间】:2018-02-09 00:39:15
【问题描述】:

我收到了cannot read property listArr of undefined 的运行时错误。我需要在多个组件中重用相同的数组。这就是我使用全局数组的原因

我已经添加了相关代码,请查看。

Global.ts:

export class Global {

    public static listArr: ObservableArray<ListItem> = new ObservableArray<ListItem>();

}

ts 文件:

 Global.listArr.push(data.items.map(item => new ListItem(item.id, item.name, item.marks)));

html 文件:

<ListView [items]="Global.listArr"  > </ListView>

【问题讨论】:

    标签: angular typescript nativescript angular2-nativescript


    【解决方案1】:

    我建议你去Shared Services。将全局数组保留在服务中,将服务标记为 app.module 中的提供者,即您的main module

    Service
    
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class Service{
    
        public static myGloblaList: string[] = [];
    
        constructor(){}
    
    
    }
    

    将其添加到 NgModuleproviders 数组中。

    现在您可以在任何组件中使用它,例如

    constructor(private service : Service){
      let globalList = this.service.myGlobalList;// your list
    }
    

    我选择服务的原因是它使用 Angular 的依赖注入,这是拥有全局变量并在组件之间共享的最佳 Angular 方式。

    如果您希望组件在推送和弹出时自动通知数组中的更改,您可以使用服务中的行为主题。LINK- 问题 2

    【讨论】:

    • 感谢您的建议。这个答案非常有效。在服务类中,似乎不需要为全局数组声明静态关键字。我能够得到预期的结果。
    【解决方案2】:

    您不能直接在模板中访问类静态属性。您需要创建该属性的实例才能使用它。


    在这种特定情况下,在引用Global.listArr 的类中创建一个实例。您可以使用此变量来推送数据并在模板中使用。这对于其他组件也将保持最新。

    Ts 文件:

    // class variable 
    globalList: Global.listArr;
    
    // use in some method 
    this.globalList.push(data.items.map(item => new ListItem(item.id, item.name, item.marks)));
    

    HTML:

    <ListView [items]="globalList"> </ListView>
    

    链接到working demo

    【讨论】:

    • 我收到编译错误property listArr doesn't exist on type Global
    • 不,我需要直接对模板使用全局数组。因为我在多个组件中重用它
    • 你必须创建一个实例。你不能这样用AFAIK。您的列表将保持更新,您不必担心。
    【解决方案3】:

    我可以告诉你不能直接在模板中引用全局变量,因为模板绑定到组件实例。您必须提供通过组件到模板的路径,以获取要呈现的全局值。虽然创建服务是一个不错的选择,但您也可以在组件上创建一个 getter 并包装全局变量。

    查看Working Demo

    这里的要点是:

    export class AppComponent  {
      
      get getListArr() {
          return Global.listArr;
        }
    }
    
    export class Global {
    
        public static listArr: string[] = [ 'a', 'b', 'c' ];
    
    }
    <!-- in your template get it this way -->
    Gloabl static list with getter: {{getListArr}}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2017-12-15
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 2019-08-04
      相关资源
      最近更新 更多