简体   繁体   English

我如何在我的服务中等待我的方法的结果?

[英]How can i await the result from my method in my service?

I have this method in my service.我的服务中有这种方法。

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)
    );
  }

In my app component I need to initialized my property as the result from the requestAvailableTrucks call.在我的应用程序组件中,我需要将我的属性初始化为 requestAvailableTrucks 调用的结果。 And after that I need to do some logic depending on the result that came from the backend.之后,我需要根据来自后端的结果做一些逻辑。 But the problem is that I don't know how can I await this method.但问题是我不知道如何等待这种方法。

When I try当我尝试

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

the other logic don't wait for the method in my service to end.其他逻辑不要等待我的服务中的方法结束。

The only think that can be done is the approach with subscribe, and to put the code there but I need to have my logic in my service and call it from my ts.file like this唯一可以做的是订阅方法,并将代码放在那里,但我需要在我的服务中包含我的逻辑并像这样从我的 ts.file 调用它

you can simply use subscribe so that it will wait for the response.您可以简单地使用 subscribe 以便它等待响应。


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

You can use the .pipe() method on an observable stream to modify the values as they come through.您可以在可观察的 stream 上使用.pipe()方法来修改通过的值。 There are various pipeable operators that allow you to transform the stream.有多种可管道操作符可让您转换 stream。 In your case, it looks like you are trying to turn a stream of "trucks array" into a stream of "location array".在您的情况下,您似乎正在尝试将“卡车阵列”的 stream 转换为“位置阵列”的 stream。 In that case, using the map() operator, something like this would work:在这种情况下,使用map()运算符,这样的事情会起作用:

ngOnInit() {
   this.locations = this.truckService.trucks.pipe(
      map(trucks => trucks.map(t => t.location))
   );
}

You aren't await ing per se, but rather transforming the values as they come through.您不是await本身,而是在价值通过时对其进行转换。 Also, you don't need to subscribe here, but you could if you really needed to.此外,您不需要在这里订阅,但如果您真的需要,您可以订阅。 Usually you can use the async pipe in the template like this:通常您可以在模板中使用async pipe,如下所示:

<h1>Truck Locations</h1>
<ul>
  <li *ngFor="let location of locations | async">
    {{ location }}
  </li>
</ul>

If you needed to do some side effect type stuff in your "other logic", you may utilize the tap operator inside the pipe() as well.如果您需要在“其他逻辑”中做一些副作用类型的事情,您也可以在pipe()中使用tap运算符。

ngOnInit() {
   this.locations = this.truckService.trucks.pipe(
      map(trucks => trucks.map(t => t.location)),
      tap(() => this.isLoading = false)
   );
}

If you want to use await, an easy way is to convert observable to be promise.如果要使用 await,一个简单的方法是将 observable 转换为 promise。

async ngOnInit() {
  this.trucks = await this.truckService.trucks.toPromise();
  // other logics
}

You can actually convert every observable api call to be promise, then you will be able to forget everything about stream.您实际上可以将每个可观察到的 api 调用转换为 promise,然后您将能够忘记 stream 的所有内容。 Just think in regular promise ways.想想常规的 promise 方式。

For a more reactive way:对于更被动的方式:

  1. For the service, I do not thing you need to wrap the logic int a get:对于服务,我不需要将逻辑包装为 get:
class TruckService {
  trucks$ = this.requestAvailableTrucks().pipe(
    shareReplay(CACHE_SIZE)
  );

  requestAvailableTrucks() {...}
}
  1. Then you can just call it in the component, and take advantage of async pipe.然后你可以在组件中调用它,并利用异步 pipe。 The code would be like:代码如下:
tracks$ = this.truckService.tracks$;
ngOnInit() {....}

// TEMPLATE
{{tracks$ | async}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在服务中创建一个返回 onSnapshot 结果的方法,然后在我的组件或 Ionic 页面中使用它? - How can I create a method in a service that returns the result of onSnapshot and then using it in my Component or Ionic Page? 当我订阅我的服务方法(执行查询)时,如何检索从 FireStore DB 检索到的每个文档的 UID? - How can I retrieve the UID of each document retrieved from FireStore DB when I subscribe my service method (performing the query)? 如何通过服务访问我的商店? - How can I access my Store from a service? 我如何等待 setInterval 的结果,以便我可以从自定义管道以 angular 返回它? - How can i await the result from setInterval so i can return it from the custom pipe in angular? 如何将查询参数从我的前端服务传递到我的服务器? - How can I pass a query param from my service on the front end to my server? 使用服务从数据库中获取数据时,如何显示和隐藏简单的CSS微调器-Angular 2&gt; - How can I show & hide simple CSS spinner while fetching data from database with my service - Angular 2> 当我的服务的构造函数中有可注入对象时,如何将服务注入我的测试中? - How can I Inject a Service into my test when my service has an injectable in its constructor? 我如何在不从我的服务传递属性“类型”的情况下使用带有元数据的效果? - How i can use effects with metadata without passing the property “type” from my service? 我正在尝试使用async / await来获取服务,但是第二个服务返回并没有填充我的变量 - I'm trying to use async/await to get a service, but the second service returns don't fill my variables 如何修复我的数据无法从服务中获取到Angular中的模块 - How can I fix my data not getting from service to module in Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM