我有一个表单,我允许用户在刷新按钮上单击任意次数。当然,我使用debounceTime
运算符,但我不知道如何:
例如:
因此,我将从 t1 时刻获取数据,而最新的数据是在 t2 时刻。
我试过pipe(last())
,switchMap
但我不返回数据。
我的组件:
this.filtersForm.valueChanges.pipe(debounceTime(500)).subscribe(
form => {
this.service.setFilters(form); // Set private field in service (1)
this.onSubmit();
}
);
onSubmit() {
if (this.filtersForm.valid) {
this.service.notifFiltersHasChanged();
}
}
服务:
ctor(...) {
this.filters$.subscribe(f => this.getData());
}
notifFiltersHasChanged() {
this.filters$.next(this._filters); // (1) _filters is set by setFilters method
}
getData(): void {
// ...
this.backEndService.getAll(this._filters).subscribe(data => this._data = data);
}
后端服务:
getAll(filters: any): Observable<Data> {
return this.httpClient.get<Data>(url).pipe(last());
}
主要技巧是使用单个订阅(如果您将| async
在模板中使用管道,则甚至为零)。所以你从一个 Observable 中获取资源并通过你的服务链。
这是您的更新示例:
成分
onDestroy$ = new Subject<void>();
constructor(){
this.filtersForm.valueChanges.pipe(
// accept only valid values
filter(() => this.filtersForm.valid),
// debounce them
debounceTime(500),
// when a value comes in -- we switch to service request
// subsequent values would cancel this request
switchMap(formValues => this.service.getData(formValues)),
// this is needed to unsubscribe from the service
// when component is destroyed
takeUntil(this.onDestroy$)
)
.subscribe(data=>{
// do what you need with the data
})
}
ngOnDestroy() {
this.onDestroy$.next(void 0);
}
服务
// service becomes stateless
// its only responsible for parsing and passing data
getData(filters): Observable<Data> {
return this.backEndService.getAll(filters);
}
后端服务
getAll(filters: any): Observable<Data> {
return this.httpClient.get<Data>(url).pipe(last());
}
另一种方法是有一个Subject
, 你会推到。否则,它会是相同的链接Subject
。
希望这可以帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句