Just getting to grips with the nuances of Angular 2 and one thing I'm trying to establish is the best practice for creating site wide variables that can be used in any component.
I am pulling variables from the db with a service. That service has a getVars() method which uses the Http.get() method to pull the data. My question is, rather than use that method each time I need the variables, can I use it once and store it in a constant variable ( or similar ) then call that anytime I need it. And would that be in the root module?
One thing to know is that all the Injectable
are Singleton
in an Angular 2 application. You can just retrieve your value with your method (basically on initialization, check APP_INITIALIZER
), store it in a property of your object and then retrieve it everywhere you inject your service. Here's a short example for a configuration service.
config.service.ts
@Injectable()
export class ConfigService {
private _config: Object;
private http: Http;
constructor(private injector: Injector) {
}
get(optionName: any) {
return this._config[optionName];
}
load() {
this.http = this.injector.get(Http);
let observable = this.http.get('dist/config/configuration.json')
.map(res => res.json());
observable.subscribe(config => this._config = config);
return observable.toPromise();
}
}
In your App.module.ts in your Providers
array
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: (config: ConfigService) => () => config.load(),
deps: [ConfigService],
multi: true
},
Then you can just inject your service into every Component and access the variable directly with configService.get('yourVariable')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With