I encounter the following problem: I want to create a singleton class that store the configuration for the client. The configuration comes from an SQL server that is retrieved via an API in ASP.net.
Now let's say Home component use the singleton instance to retrieve the configuration.
How do I make sure that the home component waits with retrieving the data from the singleton after the singleton is finished? Since this configuration is static I would like to load it only once.
Example
Singleton:
constructor(appConfig:AppConfigService,private http: HttpClient) {
if(!ClientconfigurationService.instance){
ClientconfigurationService.instance = this;
}
this.apiUrl = appConfig.data.API_URL;
this.getColumns().then(result => this.clientConfiguration.userClientConfiguration.patientOverviewColumnConfig = result)
}
async getColumns():Promise<PatientOverviewColumnConfig[]>{
const url = this.apiUrl+'/ColumnConfig/GetColumnConfiguration'
const response = this.http.get<PatientOverviewColumnConfig[]>(url)
this.columns = await lastValueFrom(response);
return this.columns;
}
getPatientOverViewColumns():PatientOverviewColumnConfig[] {
return this.clientConfiguration.userClientConfiguration.patientOverviewColumnConfig;
}
From the home component:
ngOnInit(): void {
this.columns = this.clientconfigurationService.getPatientOverViewColumns();
}
But this.columns is empty. most likely because the data is not there yet? Am I missing something? Or is the design wrong here?
The following piece of code is not asyncronous:
this.getColumns().then(result => this.clientConfiguration
.userClientConfiguration.patientOverviewColumnConfig = result)
So there is no data in this.clientConfiguration.userClientConfiguration.patientOverviewColumnConfig
when your home component is initialized.
It is possible to move the above rows in separate method:
async getColumnConfig(): PatientOverviewColumnConfig {
await this.getColumns();
}
and then in your home component:
async ngOnInit(): void {
this.columns = await this.clientconfigurationService.getColumnConfig();
}