Angular 如何将HTTP请求限制为每2秒一次
我使用的是Ionic 2(Angular 2),我有一个自动完成功能,每次键入一个单词时都会发出API请求。我想将其更改为每2秒一次,但我无法使用Angular 如何将HTTP请求限制为每2秒一次,angular,ionic-framework,Angular,Ionic Framework,我使用的是Ionic 2(Angular 2),我有一个自动完成功能,每次键入一个单词时都会发出API请求。我想将其更改为每2秒一次,但我无法使用throttleTime和debounceTime 服务台 search(keyword): Observable<any> { let URL = `${this.api}/products/${keyword}`; return this.authService.refreshToken() .flatMap
throttleTime
和debounceTime
服务台
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();
}
你可以在angular2中使用可见光 导入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);
});
将
debounce
属性添加到ion搜索栏
debounce
-输入类型number
,等待触发
在每次击键后输入事件。默认为250
这里有一个适合我的解决方案,以防有人需要
.html
那么,您现在是否希望它每2秒发送一次请求,而不管用户是否键入内容?不,只有在用户键入内容之后才发送请求(因此,当http请求在search()中发出时)
这对我来说不起作用,因为我首先向api发出http请求以刷新令牌,然后再进行调用。这对我来说不起作用,即使它在ionic文档中。它仍然会对我键入的每一个单词发出请求,然后你就会这样做出现问题。请尝试删除除输入和去盎司外的所有输入。在每个函数中,只需控制台记录值。放置一个ngmodel并传入函数。它不起作用,我复制并粘贴了它
onSearch(event) {
let keyword = event.target.value;
this.searchProductsService.search(keyword)
.subscribe(
(products: Pinterface[]) => {
this.products = products;
},
(error: Response) => {
console.log(error);
});
}
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);
});
<ion-searchbar
[showCancelButton]="true"
[placeholder]="'Search for a Product'"
[autocomplete] = "on"
(input)="onSearch($event)"
[debounce]="2000"
</ion-searchbar>
<ion-searchbar
[formControl]="searchControl"
[(ngModel)]="searchTerm">
</ion-searchbar>
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
});
}