Home > Back-end >  cannot make debouncetime to work with an observable
cannot make debouncetime to work with an observable

Time:08-24

I want to when user finish writing in input box make the request, i have tried with debounceTime so it can make a 3 seconds delay before making the query but i don't know how to implement in my case, most examples with rxjs are in the component but not in a service call. Thanks

//HTML

 <input _ngcontent-juw-c105="" placeholder="Buscar" type="text" id="edit-combine" name="searchFilter" value="" size="30" maxlength="128"  style="width: 100%;" ng-reflect-maxlength="128" ng-reflect-name="combine" [ngModel]='titulo' (keyup)='setFiltered()'>

//Component

ngAfterContentInit() {
    this.tituloSub = this.valueChanged
      .pipe(debounceTime(3000))
      .subscribe((data) => {
        this.setFiltered();
      });
  }

  setFiltered() {
    this.loader = true;
        this.buscadorService.getNodes()
        .subscribe((data: InformesCounter) => {
          this.loader = false;
          this.buscadorService.pageNumber = this.page;
          this.informesNode = data.data;
          this.nid = this.informesNode.map((data: { id: any;}) => data.id);
          console.log("test");
          this.nodeList = this.informesNode.map((data: { attributes: any;}) => data.attributes);
          this.showResolucion();
          this.showInforme();
          this.showFicha();
          this.showDifusion();
      });
  }

//Service

  getNodes(): Observable<InformesCounter> {
    this.pageNumber = 1;
    return this.http.get<InformesCounter>(`${this.informesNodes}`); //myuri is in informesNodes
  }

CodePudding user response:

Ok so your on the right track, but you need to make a few changes, create a subject, which will be subscribed with debounce time, and calls the search method. Then in the keyup or change event you can call the next method of the subject which will be recieved in the subscribe we wrote earlier and finally perform the search if the debounce time condition is met!

html

<input
  placeholder="Search"
  [(ngModel)]="searchStr"
  (ngModelChange)="triggerSearch()"
/>

ts

import { Component, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { fromEvent, Subject } from 'rxjs';
import {
  filter,
  debounceTime,
  distinctUntilChanged,
  tap,
} from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  searchSubject: Subject<any> = new Subject<any>();
  searchStr = '';

  ngAfterViewInit() {
    // server-side search
    this.searchSubject.pipe(debounceTime(1500)).subscribe(() => {
      console.log('do the action here for the value: ', this.searchStr);
    });
  }

  triggerSearch() {
    this.searchSubject.next();
  }
}

forked stackblitz

  • Related