无法使用debounceTime()或throttleTime()来处理Angular http请求

时间:2017-05-25 14:50:12

标签: angular rxjs5

对于我的生活,我无法做到这一点。 我搜索过并搜索过,但我找不到任何示例(所有示例都包含F36public freshPOST() { //declare ESO login page as well as open Inappbrowser var url_code: any; let url = "CLIENT_AUTH_ENDPOINT_URL"; let browser = new InAppBrowser(url, '_blank', 'location=no,zoom=yes,enableViewportScale=yes,toolbar=no'); //on redirect browser shows load error, and not url browser.on("loaderror").subscribe((event: InAppBrowserEvent) => { //pull code from url and store in variable let token = event.url.split('=')[1].split('&')[0]; url_code = token; localStorage.setItem('url_code', url_code); //SETUP FOR POST //headers to be sent var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let options = new RequestOptions({ headers: headers }); //parameters for POST request let details = "code=" + url_code + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=REDIRECT_URI&grant_type=authorization_code"; //POST request with parameters injected this.http.post('CLIENT_TOKEN_ENDPOINT', details, options) .map(res => res.json()) .subscribe( data => { //convert response to string, pull access token, and store in variable this.data = JSON.stringify(data) var access_token = data.access_token; var expires_in = data.expires_in; var refresh_token = data.refresh_token; //store all responses to local storage for retrieval localStorage.setItem('access_token', access_token); localStorage.setItem('expires_in', expires_in); localStorage.setItem('refresh_token', refresh_token); //launch app //write to console success //close browser console.log("Successful POST and Authentication"); browser.close(); Splashscreen.hide(); }, (err) => { //POST Failure //close browser console.log("post didnt work"); }); }); } 没有。)

在我的模板中,我有这个输入:

.fromEvent()

在我的组件中,我有以下内容:

http.get

这是我的ApiService中的方法:

<input type="text" (input)="categoriesSearch($event)">

categoriesSearch(event) { this.categoriesSubscription = this.apiService .getCategoriesList(this.uploadForm.get('categories').value) .debounceTime(3000) // .throttleTime(3000) .subscribe( (response) => { this.categories = response.data; } ); } 方法中,我同时尝试了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()

但http.get请求根本没有被去除或限制!如果我在3秒内输入10个字符,则会产生10个http请求。

如果自上一次请求后至少已经过了3秒,或者“没有请求”,我该如何告诉import 'rxjs/add/operator/debounceTime'仅提出请求? (意思是最初的3秒延迟)?好的,也许在这里我应该说&#34;因为我在输入中输入了一些东西&#34;。

我还尝试在import 'rxjs/add/operator/throttleTime'运算符之前直接在服务中使用debounceTime()/ throttleTime(),但结果是一样的。

2 个答案:

答案 0 :(得分:8)

  

但http.get请求根本没有被去除或限制!如果我   在3秒内输入10个字符,它会产生10个http请求。

以错误的方式实施。你首先需要捕获输入,应用deounce并执行HTTP请求。

您可以通过多种方式实施

1)Observable.fromEvent

 <input type="text" #input>

组件

 @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)使用主题

<input type="text" (keyup)="search($event)">

组件

  searchTerms = new Subject<string>();

search(term: string): void {
    this.searchTerms.next(term);
  }

ngOnInit(): void {

    this.searchTerms
      .debounceTime(3000)
      .distinctUntilChanged()
      .switchMap(() => getCategoriesList())
      .subscribe(term => { 
       console.log();
     });

3)使用表单控件

 <input type="text" [formControl]="term">

成分<​​/ P>

  term = new FormControl();

  ngOnInit() {
    this.items = this.term.valueChanges
                 .debounceTime(3000)
                 .distinctUntilChanged()
                 .switchMap(term => getCategoriesList(term))
                 .subscribe(res => console.log(res));
  }

答案 1 :(得分:-4)

使用表单控件

 <input type="text" [formControl]="term">

成分<​​/ P>

term = new FormControl();

  ngOnInit() {
    this.items = this.term.valueChanges
                 .debounceTime(3000)
                 .distinctUntilChanged()
                 .switchMap(term => getCategoriesList(term))
                 .subscribe(res => console.log(res));
  }