首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何等待单个组件为其他组件做好准备?

如何等待单个组件为其他组件做好准备?
EN

Stack Overflow用户
提问于 2022-11-08 12:11:26
回答 1查看 32关注 0票数 2

我遇到了以下问题:我想要创建一个存储客户端配置的单例类。配置来自通过ASP.net中的API检索的SQL服务器。

现在假设Home组件使用单例实例来检索配置。

如何确保主组件在单例完成后等待从单例检索数据?由于这个配置是静态的,所以我只想加载它一次。

示例

辛格尔顿:

代码语言:javascript
复制
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;
}

来自家庭部分:

代码语言:javascript
复制
ngOnInit(): void {
     this.columns = this.clientconfigurationService.getPatientOverViewColumns();
  }

但是this.columns是空的。很可能是因为数据还没有呢?我是不是遗漏了什么?还是这里的设计错了?

EN

回答 1

Stack Overflow用户

发布于 2022-11-08 15:35:00

以下代码不是异步代码:

代码语言:javascript
复制
this.getColumns().then(result => this.clientConfiguration
    .userClientConfiguration.patientOverviewColumnConfig = result)

因此,当您的主组件初始化时,this.clientConfiguration.userClientConfiguration.patientOverviewColumnConfig中没有数据。

可以用单独的方法移动上面的行:

代码语言:javascript
复制
async getColumnConfig(): PatientOverviewColumnConfig {
    await this.getColumns();
}

然后在你的家庭里:

代码语言:javascript
复制
async ngOnInit(): void {
     this.columns =  await this.clientconfigurationService.getColumnConfig();
}   
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74360533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档