等到订阅完成,然后转到下一部分代码

卡拉姆

在设置其他所有内容后调用订阅,但我想等到订阅结束。

尝试使用 async await 但这对我不起作用。不确定我是否做错了

public getGlobeConfig() {
    this.sourceKey = 'test';query = 'query'
    // wait till this call finishes than hit the 
     console.log('htting')
    this.service
    .searchQuery(query)
    .subscribe(response => {
        this.sources = response.hits.hits.map(hit => 
        hit._source);
        if (this.sources.length > 0) {
            this.availableMetadata = Object.keys(
                this.sources[0].metadata[this.sourceKey]
            );
        }
    });
    console.log('hitting')
    return this.sources
}

This.sources 达到未定义状态,因为 this.sources 是在订阅中设置的

山姆赫尔曼

简短的回答是您不能在订阅后导致代码等待。话虽如此,通过退后一步查看您的代码,您不应该在该getGlobeConfig方法中订阅您可能应该做的是mapgetGlobeConfig方法中使用运算符并让方法的使用者getGlobeConfig订阅:

public getGlobeConfig() {
  // ...
  return this.service.searchQuery(query).pipe(
    map(response => {
      // Transform the response to what you want
      // the consumer of this method to receive
    })
  );
}

消费者:

getGlobeConfig().subscribe(sources => /* ... */)

我从新的 RxJs 开发人员那里看到的一个非常常见的陷阱是,他们尝试订阅服务中的 Observables,然后想要将数据返回给组件。在大多数情况下,您不会在服务内订阅。让服务对 RxJs 运算符中的数据进行操作,并让服务返回转换后的 Observable。最终消费者(通常是组件)将订阅服务返回的 Observable。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章