How to implement a debounce time in keyup event in Angular 6

后端 未结 7 2022
盖世英雄少女心
盖世英雄少女心 2020-12-05 17:57

I create an Angular app that search students from API. It works fine but it calls API every time an input value is changed. I\'ve done a research that I need something calle

7条回答
  •  温柔的废话
    2020-12-05 18:16

    Also, you can use angular formControls to bind the input search field

    
    

    and use valueChanges observable on our searchField to react to changes of out search field in your App.component.ts file.

    searchField: FormControl; 
    
    ngOnInit() {
        this.searchField.valueChanges
          .debounceTime(5000) 
          .subscribe(term => {
        // call your service endpoint.
          });
    }
    

    optionally you can use distinctUntilChanged ( which only publishes to its output stream if the value being published is different from the previous one)

    searchField: FormControl; 
    
    ngOnInit() {
        this.searchField.valueChanges
          .debounceTime(5000) 
         .distinctUntilChanged()
         .subscribe(term => {
                // call your service endpoint.
          });
    }
    

提交回复
热议问题