如何在Angular 6的keyup事件中实现去抖时间 [英] How to implement a debounce time in keyup event in Angular 6

查看:141
本文介绍了如何在Angular 6的keyup事件中实现去抖时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Angular应用,可以从API搜索学生.它工作正常,但是每次输入值更改时都会调用API.我已经进行了一项研究,需要防弹跳"功能,但我不知道如何在我的应用程序中实现该功能.

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 called debounce ,but I don't know how to implement this in my app.

App.component.html

    <div class="container">
  <h1 class="mt-5 mb-5 text-center">Student</h1>
<div class="form-group">
  <input  class="form-control form-control-lg" type="text" [(ngModel)]=q (keyup)=search() placeholder="Search student by id or firstname or lastname">
</div>
 <hr>
 <table class="table table-striped mt-5">
    <thead class="thead-dark">
      <tr>
        <th scope="col" class="text-center" style="width: 10%;">ID</th>
        <th scope="col" class="text-center" style="width: 30%;">Name</th>
       <th scope="col" style="width: 30%;">E-mail</th>
        <th scope="col" style="width: 30%;">Phone</th> 
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let result of results">
        <th scope="row">{{result.stu_id}}</th>
        <td>{{result.stu_fname}} {{result.stu_lname}}</td>
         <td>{{result.stu_email}}</td>
        <td>{{result.stu_phonenumber}}</td> 
      </tr>
    </tbody>
  </table>
</div>

App.component.ts

import { Component} from '@angular/core';
import { Http,Response } from '@angular/http';
import { Subject, Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {


  results;
  q = '';

  constructor(private http:Http) {


  }


  search() {
    this.http.get("https://www.example.com/search/?q="+this.q)
    .subscribe(
      (res:Response) => {
          const studentResult = res.json();
          console.log(studentResult);
          if(studentResult.success) {
            this.results = studentResult.data;
          } else {
            this.results = [];
          }
      }
    )
  }
}

屏幕截图

我已经尝试过类似的操作,但这是错误的 属性debounceTime在主题< {}>

I've tried something like this but it's error Property debounceTime does not exist on type Subject<{}>

  mySubject = new Subject();
  constructor(private http:Http)  {
    this.mySubject
    .debounceTime(5000)
    .subscribe(val => {
      //do what you want
    });
  }

,这也不起作用. 属性"fromEvent"在类型可观察的类型"上不存在

    Observable.fromEvent<KeyboardEvent>(this.getNativeElement(this.term), 'keyup')

那么,实现此目标的正确方法是什么?

So, what's the correct way to implement this ?

谢谢.

推荐答案

在组件中,您可以执行以下操作.创建RxJS Subject,在keyup事件中调用的search方法中,对创建的Subject执行.next().然后,如下面的代码所示,ngOnInit()中的subscribedebounce保持1秒钟.

In the component you can do somthing like this. Create RxJS Subject, In search method which is called on keyup event, do .next() on this Subject you have created. Then subscribe in ngOnInit() will debounce for 1 second, as in below code.

searchTextChanged = new Subject<string>();
constructor(private http:Http) {

}


ngOnInit(): void {
    this.subscription = this.searchTextChanged
        .debounceTime(1000)
        .distinctUntilChanged()
        .mergeMap(search => this.getValues())
        .subscribe(() => { });
}

getValues() {
    return this.http.get("https://www.example.com/search/?q="+this.q)
    .map(
      (res:Response) => {
          const studentResult = res.json();
          console.log(studentResult);
          if(studentResult.success) {
            this.results = studentResult.data;
          } else {
            this.results = [];
          }
      }
    )
}

search($event) {
    this.searchTextChanged.next($event.target.value);
}

rxjs v6进行了一些重大更改,包括简化了操作员的导入点.尝试安装rxjs-compat,它会重新添加这些导入路径,直到代码被迁移为止.

rxjs v6 has several breaking changes including simplifying import points for operators. Try installing rxjs-compat, which adds back those import paths until the code has been migrated.

RxJS导入必要的运算符.以下是用于RxJS 5.x的

Import the necessary operators from RxJS. Below ones are for RxJS 5.x

import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/debounceTime";
import "rxjs/add/operator/distinctUntilChanged";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/mergeMap";

这篇关于如何在Angular 6的keyup事件中实现去抖时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆