我遇到了以下问题:我想要创建一个存储客户端配置的单例类。配置来自通过ASP.net中的API检索的SQL服务器。
现在假设Home组件使用单例实例来检索配置。
如何确保主组件在单例完成后等待从单例检索数据?由于这个配置是静态的,所以我只想加载它一次。
示例
辛格尔顿:
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;
}来自家庭部分:
ngOnInit(): void {
this.columns = this.clientconfigurationService.getPatientOverViewColumns();
}但是this.columns是空的。很可能是因为数据还没有呢?我是不是遗漏了什么?还是这里的设计错了?
发布于 2022-11-08 15:35:00
以下代码不是异步代码:
this.getColumns().then(result => this.clientConfiguration
.userClientConfiguration.patientOverviewColumnConfig = result)因此,当您的主组件初始化时,this.clientConfiguration.userClientConfiguration.patientOverviewColumnConfig中没有数据。
可以用单独的方法移动上面的行:
async getColumnConfig(): PatientOverviewColumnConfig {
await this.getColumns();
}然后在你的家庭里:
async ngOnInit(): void {
this.columns = await this.clientconfigurationService.getColumnConfig();
} https://stackoverflow.com/questions/74360533
复制相似问题