作者:图片哪天能显示 | 来源:互联网 | 2023-02-02 20:53
对于我的生活,我无法做到这一点.我搜索过并搜索过,但是我找不到任何例子(所有的例子都有.fromEvent()
,没有一个http.get
).
在我的模板中,我有这样的输入:
在我的组件中,我有以下内容:
categoriesSearch(event) {
this.categoriesSubscription = this.apiService
.getCategoriesList(this.uploadForm.get('categories').value)
.debounceTime(3000)
// .throttleTime(3000)
.subscribe(
(response) => {
this.categories = response.data;
}
);
}
这是我的ApiService中的方法:
getCategoriesList(keyword = null) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Bearer', this.authService.user.token);
const getParams: URLSearchParams = new URLSearchParams();
getParams.set('keyword', keyword);
return this.http.get(this.apiHost + '/categories', { headers: headers, search: getParams })
.map(respOnse=> response.json());
}
在该categoriesSearch()
方法中,我都试过debounceTime()
和throttleTime()
(我还进口了他们,当然import 'rxjs/add/operator/debounceTime'
,import 'rxjs/add/operator/throttleTime'
).
但http.get请求根本没有被去除或限制!如果我在3秒内输入10个字符,则会产生10个http请求.
this.http.get
如果自上次请求后至少已经过了3秒或者"没有请求"(意味着最初的3秒延迟),我怎么告诉我只提出请求?好吧,也许在这里我应该说"因为我最后输入了一些内容".
我也尝试在.map()
运营商之前直接在服务中使用debounceTime()/ throttleTime()- 但结果是一样的.
1> CharanRoot..:
但http.get请求根本没有被去除或限制!如果我在3秒内输入10个字符,则会产生10个http请求.
你以错误的方式实施.您首先需要捕获输入,应用deounce并执行HTTP请求.
你可以用几种方式实现
1)Observable.fromEvent
零件
@ViewChild('input') text: ElementRef;
ngAfterViewInit() {
let text$ = Observable.fromEvent(this.text.nativeElement, 'keyup')
.do(() => console.log("keyup"))
.debounceTime(3000)
.distinctUntilChanged()
.switchMap(() => getCategoriesList())
.subscribe(res => console.log(res));
}
2)使用主题
零件
searchTerms = new Subject();
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.searchTerms
.debounceTime(3000)
.distinctUntilChanged()
.switchMap(() => getCategoriesList())
.subscribe(term => {
console.log();
});
3)使用表单控件
零件
term = new FormControl();
ngOnInit() {
this.items = this.term.valueChanges
.debounceTime(3000)
.distinctUntilChanged()
.switchMap(term => getCategoriesList(term))
.subscribe(res => console.log(res));
}