首页 > 解决方案 > 我如何在我的服务中等待我的方法的结果?

问题描述

我的服务中有这种方法。

get trucks() {
    if (!this.cache$) {
      this.cache$ = this.requestAvailableTrucks().pipe(
        shareReplay(CACHE_SIZE)
      );
    }
    return this.cache$;
  }

  private requestAvailableTrucks() : Observable<Array<any>> {
    return this.http.get<any>(API_ENDPOINT_TRUCKS).pipe(
      map(response => response.value)
    );
  }

在我的应用程序组件中,我需要将我的属性初始化为 requestAvailableTrucks 调用的结果。之后,我需要根据来自后端的结果做一些逻辑。但问题是我不知道如何等待这种方法。

当我尝试

ngOnInit() {
   this.locations = this.truckService.trucks;
    ... The other logic ...
}

其他逻辑不要等待我的服务中的方法结束。

唯一可以做的是订阅方法,并将代码放在那里,但我需要在我的服务中包含我的逻辑并像这样从我的 ts.file 调用它

标签: angulartypescriptrxjs

解决方案


您可以简单地使用 subscribe 以便它等待响应。


    ngOnInit() {
       this.truckService.trucks.subscribe(trucks => {
          this.locations = trucks;
       });
    }


推荐阅读