问题描述
我有一个按钮,其点击事件处理程序设置为一个函数:<button (click)="someFunction(test1)">get stuff</button>
someFunction()
做了一些事情,但它调用了一个执行 http get 的服务函数.
this._myService.getDetails(username).pipe(油门时间(10000)).订阅()
在我的服务中:
getDetails(username: string) {返回 this._http.get(url);}
这显然行不通,因为每次我点击按钮都会发出一个新的 http get 调用.
设置类似throttleTime() 的功能的好方法是什么?在特定超时长度后发出http get 调用?
你确实需要一个 throttleTime
(参见下面的对比弹珠图)
目前您正在限制响应流,而您需要限制按钮点击流.
为此,我们可以创建一个按钮点击流:
class Component {btnClickSubject$ = new Subject();一些函数(){this.btnClickSubject$.next(void 0);}}
然后 *Map
到 http-get 请求:
class Component {//...destroy$ = new Subject();ngOnInit() {this.btnClickSubject$.pipe(//限制点击次数油门时间(3000),//switchMap 或其他 *Map 操作符切换到 http-getswitchMap(() => this._http.get('url')),//完成组件销毁 *takeUntil(this.destroy$)).subscribe(response => console.log(response))}ngOnDestroy() {this.destroy$.next(void 0);}}
* 请注意,我们需要通过组件onDestroy"明确告诉此订阅完成
--
这里是
希望能帮到你
I have a button whose click event handler is set to a function: <button (click)="someFunction(test1)">get stuff</button>
someFunction()
does some stuff but then it calls a service function that does a http get.
this._myService.getDetails(username).pipe(
throttleTime(10000)
).subscribe()
In my service:
getDetails(username: string) {
return this._http.get(url);
}
This obviously won't work because every time I click the button a new http get call is issued.
What would be a good way of setting up a throttleTime()-like functionality where http get calls are issued after a certain time out length?
You do need a throttleTime
(see the comparative marble diagram below)
Yet currently you're throttling the response stream, instead you need to throttle your button click stream.
To do so, we can create a stream out of button clicks:
<button (click)="someFunction(test1)">get stuff</button>
class Component {
btnClickSubject$ = new Subject<void>();
someFunction(){
this.btnClickSubject$.next(void 0);
}
}
And then *Map
it to the http-get request:
class Component {
//...
destroy$ = new Subject<void>();
ngOnInit() {
this.btnClickSubject$.pipe(
// throttle clicks
throttleTime(3000),
// switchMap or other *Map operator to switch to http-get
switchMap(() => this._http.get('url')),
// complete with component destroy *
takeUntil(this.destroy$)
)
.subscribe(response => console.log(response))
}
ngOnDestroy() {
this.destroy$.next(void 0);
}
}
* Note that we need explicitly tell this subscription to complete with component "onDestroy"
--
And heres a comparison of debounceTime vs throttleTime vs auditTime vs sampleTime
Hope this helps
这篇关于正确设置throttleTime() 操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!