Reputation: 493
I have global settings in application, that are stored in local storage.
I need to write service that is launched at ones after loading application to load settings from local storage.
Where to do that?
I can write service and call this in each components, but it is not convenient.
Upvotes: 0
Views: 65
Reputation: 7242
you can create resolve and call service one time when your application load
see the example how to use
also you can create getter and setter methods so you easily access in every component
for example
// import
export class AppConfigService{
public token: string;
Constructor(private http: Http){
}
get token(): string{
return this.token;
}
getAppConfig(): Promise<any> {
return this.http.get('apiBaseUrl')
.toPromise()
.then(resp => {
this.token = res.token;
}).catch(function (err: any): any {
Observable.throw(err);
});
}
}
solution 2
Put this function into app module
export function loadAppConfig(appService: AppConfigService): Function {
return () => appService.getAppConfig();
}
add this into providers
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: loadAppConfig,
deps: [AppConfigService],
multi: true
},
]
Upvotes: 2
Reputation: 68665
You can load settings from the local storage in the constructor of the service. When the service will be loaded first time, settings will be loaded. But be sure that the service will be singleton across application. The usage of your service is shared across your application.
Upvotes: 1