Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot read property global array of undefined in nativescript angular2

I got a runtime error as cannot read property listArr of undefined. I need to reuse that same array in multiple components. That's why I'm using Global array

I have added relevant code.please check it.

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>
like image 875
Steve Avatar asked Aug 31 '17 06:08

Steve


1 Answers

I would suggest you to go for Shared Services. Keep the global array in the service mark the service as a provider in app.module i:e your main module.

Service

import { Injectable } from '@angular/core';

@Injectable()
export class Service{

    public static myGloblaList: string[] = [];

    constructor(){}


}

add it to providers array of NgModule.

Now you can use it in any Component like

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

The reason i opt for a service is it uses Angular's Dependency Injection and it is the best Angular way to have a global variable and have it shared across Components.

And if you want the component to be auto notified of the changes in the array while push and pop you can make use of Behaviour subject in Services.LINK- question 2

like image 100
Rahul Singh Avatar answered Oct 02 '22 02:10

Rahul Singh