The injectable SharedService class could be used to share application configuration coming from back-end with components. In fact, in the SharedService we will call the BE in order to retrieve the main application configuration. After that, through the subscribe() function we will access to the returned data.
shared.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class SharedService{ sharedVariable: string; private readonly CONFIG_URL = 'http://dodu.it:8081/'; private configuration: Observable<Configuration>; constructor(private http: HttpClient){ this.sharedVariable = 'Hello World!'; } getConfiguration(): Observable<Configuration> { if (!this.configuration) { this.configuration = this.http.get<Configuration>(this.CONFIG_URL).pipe(shareReplay(1)); } return this.configuration; } setSharedVariable(val: string){ this.sharedVariable = val; } getSharedVariable(): string{ return this.sharedVariable; } }
app.module.ts
@NgModule({ ... providers: [ SharedService ], bootstrap: [ AppComponent ] }) export class AppModule { }
my.component.ts
constructor(private mySharedService: SharedService) { } updateSharedVariable(val){ this.mySharedService.setSharedVariable(val); } retrieveSharedVariable(){ alert("Shared variable: " + this.mySharedService.getMyGV()); } retrieveBEConfiguration(): void { this.mySharedService.getConfiguration().subscribe(data => { console.log(data); }); }