【发布时间】:2022-06-10 20:27:15
【问题描述】:
Angular RxJS 代码进行 API 调用以从 API 服务获取信息 但是,我需要每秒发出一次请求。我知道我需要使用 Observables 但不知道如何继续。
【问题讨论】:
-
仅供参考:您可以将对象用于 forkJoin 而不是数组,因此您不必在管道中映射它
标签: angular rxjs observable
Angular RxJS 代码进行 API 调用以从 API 服务获取信息 但是,我需要每秒发出一次请求。我知道我需要使用 Observables 但不知道如何继续。
【问题讨论】:
标签: angular rxjs observable
您可以使用 rxjs interval 运算符进行轮询。
【讨论】:
timer(0, 1000) 将立即开始。
这种方法应该很好用(在伪代码中)
interval
pipe(
exhaustMap
forkJoin
)
注意:如果forkJoin的时间超过1s,exhaustMap会忽略interval事件,然后每隔1s继续一次
【讨论】:
您可以使用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) {}
}
注意:请参阅intercept service 了解虚拟网络 API 的工作原理。如果存在实际 API,则不需要这样做。
【讨论】: