job.answiz.com
  • 1
Votes
name

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>

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

  • 0
Reply Report