2017-07-25 63 views
0

我正在使用Ionic 2(Angular 2),並且我有一個自動完成功能,每次鍵入一個單詞時都會發出一個API請求。我想改變這種狀況,以每2秒,但我用throttleTimedebounceTime如何限制HTTP請求到每2秒

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

所以做你現在希望它每隔2秒發送一個請求**不管用戶是在輸入什麼東西? – 0mpurdy

+0

不僅在用戶鍵入內容後(所以當在'search()'中產生http請求時) – Anonguy123

回答

0

您可以在angular2中使用observables 導入反應js庫,然後調用間隔函數。 如果我沒有偷懶的財產以後意外的話,這應該工作:

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); 
     }); 
+0

這不會對我有用,因爲我首先向我的api發出一個http請求來刷新令牌並撥打電話。 – Anonguy123

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> 
+0

This雖然它在離子文檔中仍然不起作用,但它仍然引發了我輸入每個單詞的請求 – Anonguy123

+0

然後你做錯了一些事情,嘗試移除除了輸入和去抖動之外的所有輸入在onSeach函數中,值。把一個ngmodel和傳遞函數 –

+0

現在這個工作嗎? –

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 
    }); 
}