问题
For ionic 3 - what is the best practice to share variables across the application? For example, if I have a generic variable or generic array and I want it to be available across all source files in the application, what is the best way to do it?
Should I use a provider and create getter functions or maybe there is some better and simple way to do it, such like header files in c?
回答1:
I would follow the Angular documentation for the Core-feature model. Which means creating a common module for your application wide singleton services (providers). Where you import those services and add them to the providers-list.
Then simply import the CoreModule in the AppModule, eg add it to the imports-list.
Core-module:
import { NgModule } from '@angular/core';
import { IonicModule } from 'ionic-angular';
import { FooService } from './services/foo-service';
import { BarService } from './services/bar-service';
export {
FooService,
BarService
}
@NgModule({
imports: [
IonicModule
],
providers: [
FooService,
BarService
]
})
export class CoreModule{}
By adding the
export {
FooService,
BarService
}
you can import all the services in your components from one file, like this:
import { FooService, BarService } from '../../core/core-module';
And inject and use them as usual in the constructor:
constructor(private fooService: FooService, private barService:BarService){}
someFunctionCallingServiceFunction(){
this.fooService.data; // You can access properties
this.fooService.someFunction(); // and functions
}
The file structure I use:
--core/
core.module.ts
--services/
foo.service.ts
bar.service.ts
Example service:
import { Injectable } from '@angular/core';
@Injectable()
export class FooService {
data:string;
private hiddenData:string; // Can only be used internally
constructor(){ }
someFunction(){
// Does something...
}
// Can only be used internally
private somePrivateFunction(){
// Does something else...
}
}
来源:https://stackoverflow.com/questions/45404305/ionic-3-what-is-the-best-practice-to-share-variables-across-the-application