我正在使用Ionic 2(Angular 2),我有一个自动完成功能,每次输入一个单词时都会发出API请求。我想将其更改为每2秒,但我无法使用throttleTime
和debounceTime
service.ts
search(keyword): Observable<any> {
let URL = `${this.api}/products/${keyword}`;
return this.authService.refreshToken()
.flatMap(() => this.authHttp.get(URL)
.throttleTime(10000)
.debounceTime(10000)
.map(
(response: Response) => {
return response.json().products;
},
(error: Response) => {
console.log(error);
})
.share();
}
searchbar.html
<ion-searchbar
[showCancelButton]="true"
[placeholder]="'Search for a Product'"
[autocomplete] = "on"
(input)="onSearch($event)">
</ion-searchbar>
component.ts
onSearch(event) {
let keyword = event.target.value;
this.searchProductsService.search(keyword)
.subscribe(
(products: Pinterface[]) => {
this.products = products;
},
(error: Response) => {
console.log(error);
});
}
答案 0 :(得分:0)
你可以在angular2中使用observable 导入react js库,然后调用interval函数。 如果我没有其他的东西,那么这应该工作:
import {Http} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';
Observable.interval(2000)
.switchMap(() => http.get('http://yoururl.com/products/')).map((products) =>products.json())
.subscribe(
(products: Pinterface[]) => {
this.products = products;
},
(error: Response) => {
console.log(error);
});
答案 1 :(得分:0)
将debounce
属性添加到ion-searchbar
。
debounce
- 输入类型number
,等待触发的持续时间(以毫秒为单位) 每次击键后的ionInput事件。默认250。
<ion-searchbar
[showCancelButton]="true"
[placeholder]="'Search for a Product'"
[autocomplete] = "on"
(input)="onSearch($event)"
[debounce]="2000"
</ion-searchbar>
答案 2 :(得分:0)
这是一个适用于我的解决方案,以防任何人需要一个
html的
<ion-searchbar
[formControl]="searchControl"
[(ngModel)]="searchTerm">
</ion-searchbar>
.module.ts
searchTerm: string = '';
searchControl: FormControl;
constructor() {
this.searchControl = new FormControl();
}
ionViewDidLoad() {
// Wait 7 seconds before searching
this.searchControl.valueChanges.debounceTime(700).subscribe(search => {
//Do whatever after 7 secs have passed
});
}