我想使用反应式编程编写每 5 秒刷新一次数据。
所以我定义了变量来保存我从服务器获得的项目:
items$ = new BehaviorSubject(null);
并创建另一个变量以从服务器获取请求。
为此,我interval
每 5 秒使用一次:
interval(5 * 1000).pipe(
startWith(0),
并exhaustMap
用于阻止另一个请求,直到当前将被解决。
在我调用 http 后,我将其保存items$
并切换到,items$
因为我订阅了 html 模板。(我不想订阅两次)
this.http.get(this.url).pipe(
tap((r) => {
console.log({ r });
this.items$.next(r);
}),
switchMap(() => this.items$)
问题是我只得到http
一次结果。
那么如何使interval
仍然发出值并保持刷新并切换到数据的想法呢?
完整代码codesandbox.io
@Component({
selector: "app-root",
template: ` {{ reload | async | json }} `
})
export class AppComponent {
title = "CodeSandbox";
items$ = new BehaviorSubject(null);
reload = interval(5 * 1000).pipe(
startWith(0),
exhaustMap(() =>
this.http.get(this.url).pipe(
tap((r) => {
console.log({ r });
this.items$.next(r);
}),
switchMap(() => this.items$)
)
)
);
url = "https://randomfox.ca/floof/";
constructor(private http: HttpClient) {}
}
该exhaustMap
运营商正在等待内部可观察到结束。
移动switchMap
之外exhaustMap
,并通过这样做,当http
完成那么它会切换到你items$
观察到的数据流。
reload = interval(5 * 1000).pipe(
startWith(0),
exhaustMap(() =>
this.http.get(this.url).pipe(
tap((r) => {
console.log({ r });
this.items$.next(r);
})
)
}),
switchMap(() => this.items$)
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句