【问题标题】:How to wait until service constructor called and execution completed in angular如何等到调用服务构造函数并以角度完成执行
【发布时间】:2021-07-11 22:41:49
【问题描述】:

我已使用 NgxIndexedDBService 将 api_url 存储在索引数据库中。现在我必须在服务中进行任何调用之前获取 api_url。但是当我尝试从组件的构造函数中调用任何服务方法时,它会抛出异常,因为 api_url 未定义,因为订阅方法仍在从 IndexedDB 获取数据

this.dbService.getByKey('CompanyInfo', 'test').subscribe((key: any) =>
{
    this.apiendpoint = key.API_URL;
});

请建议任何方法等到服务构造函数执行完成后再调用任何服务?或者请建议任何其他方法?

【问题讨论】:

  • 在订阅成功里面调用服务怎么样? this.dbService.getByKey('CompanyInfo', 'test').subscribe((key: any) => { this.apiendpoint = key.API_URL; // 在此之后调用服务。});

标签: angular typescript


【解决方案1】:

您可以使用一个等待 apiendpoint 有效的函数进行包装

// 创建在数据准备好时发出的主题

@Output() public apiendpointChanged: Subject<any> = new Subject();


this.dbService.getByKey('CompanyInfo', 'test').subscribe((key: any) =>
{
    this.apiendpoint = key.API_URL;
    this.apiendpointChanged.next(this.apiendpoint);
});

// 创建一个检查数据是否已经填充的函数 - 返回数据,否则等待数据填充。

  public getData(): Promise<any> {
    return new Promise((resolve, reject) => {
      try {
        if (this.apiendpoint) {
          resolve( this.apiendpoint)
        }
        else {
          const subs = this.apiendpointChanged.subscribe(data => {
          resolve( this.apiendpoint)
            subs.unsubscribe();
          })
        }
      } catch (error) {
        reject(error)
      }
    })
  }

当您需要 apiendpoint 值时,只需添加此调用: 等待 getData();

【讨论】:

    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2019-07-06
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多