【问题标题】:Receiving updates from API every second每秒从 API 接收更新
【发布时间】:2022-06-10 20:27:15
【问题描述】:

Angular RxJS 代码进行 API 调用以从 API 服务获取信息 但是,我需要每秒发出一次请求。我知道我需要使用 Observables 但不知道如何继续。

【问题讨论】:

  • 仅供参考:您可以将对象用于 forkJoin 而不是数组,因此您不必在管道中映射它

标签: angular rxjs observable


【解决方案1】:

您可以使用 rxjs interval 运算符进行轮询。

【讨论】:

  • 在这种用户情况下,它需要的不仅仅是间隔 - 需要考虑飞行中的 forkJoin
  • @Drenai 你说得对:我试着考虑一下。我还想到的是重复包装在 forkjoin 中的调用。但这并不能满足 1s 的要求。
  • 我正在写回复评论,但是太长了?
  • 仅供参考,timer(0, 1000) 将立即开始。
【解决方案2】:

这种方法应该很好用(在伪代码中)

interval
   pipe(
     exhaustMap 
        forkJoin
   )

注意:如果forkJoin的时间超过1s,exhaustMap会忽略interval事件,然后每隔1s继续一次

【讨论】:

  • 应该是公认的答案。
【解决方案3】:

您可以使用interval()x 毫秒对服务器执行一次ping 操作。您可以在pipe() 中的exhaustMap() 中执行forkJoin()

@Injectable({ providedIn: 'root' })
export class ExampleService {
  private readonly INTERVAL = 1000;

  constructor(private readonly _http: HttpClient) {}

  getInformation$(id: number): Observable<publicInformation> {
    return timer(0, this.INTERVAL).pipe(
      exhaustMap(() =>
        forkJoin({
          name: this._http.get<name>(`api/name/${id}`),
          currentInformation: this._http.get<CurrentInformations>(
            `api/currentInformation/${id}`
          ),
        })
      )
    );
  }
}

像这样订阅组件的 Observable:
注意:你也可以使用数组,这个例子只是使用了两个不同的属性。

<div *ngIf="information1$ | async as data">
  <p>Name: {{ data.name.first }} {{ data.name.last }}</p>
  <p>
    {{ data.name.first }}'s Current Time: {{ data.currentInformation.current }}
  </p>
</div>

<hr />

<div *ngIf="information2$ | async as data">
  <p>Name: {{ data.name.first }} {{ data.name.last }}</p>
  <p>
    {{ data.name.first }}'s Current Time: {{ data.currentInformation.current }}
  </p>
</div>

组件:

export class AppComponent {

  information1$ = this.exampleService.getInformation$(123);
  information2$ = this.exampleService.getInformation$(456);

  constructor(private exampleService: ExampleService) {}
}

Here is a working example

注意:请参阅intercept service 了解虚拟网络 API 的工作原理。如果存在实际 API,则不需要这样做。

【讨论】:

  • 如果 API 调用被延迟并花费了 5s,concatMap 可以存储 5 个待处理事件,然后尽快发出(忽略 1s 轮询时间)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
相关资源
最近更新 更多