1

I just started using Ionic2/Angular 2 and I'm a bit confused. Let's say I have a variable in a class like this:

export class HomePage {
    array: string[]; 
}

and I would like to use the data in the array in another class but not change it. How would I export the variable array from class HomePage to another class?

sebaferreras
  • 44,206
  • 11
  • 116
  • 134
noobdev
  • 21
  • 5

1 Answers1

0

For this you have to use Global Service/shared Service , firslt set your global variable with value globaly in your app than you are able to use that service anywheer in your app.

let suppose this is our Global service

export class GlobalService {
    array: string[]; 
}

export class HomePage {
    array: any[] = [];

    constructor(private global: GlobalService){
        this.array = this.global.array; 
    }
}

export class SecondPage {
    array: any[] = [];

    constructor(private global: GlobalService){
        this.array = this.global.array; 
    }
}

you can inject that GloablService globally in your app. like in the main module than no need to add service in the list of providers everytime. just import this and intilize in the constructor and access their method and variables

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • where do I put: export class GlobalService { array: string[]; } – noobdev Dec 24 '16 at 21:02
  • Make a separate file for the same and add the reference in app.module.ts file – Pardeep Jain Dec 25 '16 at 04:03
  • sorry man I'm a noob when it comes to Angular 2, can you explain how I can add a reference in app.module.ts and where would I create the GlobalService.ts file assuming I'm using Ionic 2 – noobdev Dec 25 '16 at 04:11
  • please take a look at new angular CLI project structure there you will find app.module.ts file and you will know about dependency injection. also create GloablService at global level/root level. sorry i dont have any idea about ionic i know about only angular2. – Pardeep Jain Dec 25 '16 at 06:46
  • thanks man! so I'm gessing I'll have to add it as a provider right? – noobdev Dec 25 '16 at 06:49
  • this is what I see in my app.module.ts: – noobdev Dec 25 '16 at 06:50
  • @NgModule({ declarations: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage ], providers: [ Storage, {provide: ErrorHandler, useClass: IonicErrorHandler}] }) export class AppModule {} – noobdev Dec 25 '16 at 06:50
  • Exactly you have to add in the list of providers I hope you get it – Pardeep Jain Dec 25 '16 at 14:24
  • says can't find name GlobalService :( – noobdev Dec 25 '16 at 19:18