如何在 Angular 6 的 keyup 事件中实现去抖动时间 [英] How to implement a debounce time in keyup event in Angular 6
问题描述
我创建了一个从 API 搜索学生的 Angular 应用.它工作正常,但每次更改输入值时都会调用 API.我做了一项研究,我需要一种叫做 debounce 的东西,但我不知道如何在我的应用中实现它.
App.component.html
<h1 class="mt-5 mb-5 text-center">学生</h1><div class="form-group"><input class="form-control form-control-lg" type="text" [(ngModel)]=q (keyup)=search() placeholder="通过id或者名字或者姓氏搜索学生"><小时><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>
<tr *ngFor="让结果的结果"><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>App.component.ts
import { Component} from '@angular/core';从@angular/http"导入 { Http,Response };从'rxjs'导入{主题,可观察};@零件({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {结果;q = '';构造函数(私有 http:Http){}搜索() {this.http.get("https://www.example.com/search/?q="+this.q).订阅((res:响应) =>{const studentResult = res.json();控制台日志(学生结果);如果(学生结果.成功){this.results = studentResult.data;} 别的 {this.results = [];}})}}
截图
我试过这样的事情,但它是错误的属性 debounceTime 不存在于类型 Subject<{}>
mySubject = new Subject();构造函数(私有 http:Http){this.mySubject.去抖动时间(5000).subscribe(val => {//做你想做的事});}
这也行不通.属性fromEvent"在类型typeof Observable"上不存在
Observable.fromEvent(this.getNativeElement(this.term), 'keyup')
那么,实现这一点的正确方法是什么?
谢谢.
解决方案 在组件中你可以做这样的事情.创建 RxJS Subject
,在 keyup
事件调用的 search
方法中,对这个 .next()
做.next()
您创建的代码>主题代码>.然后 ngOnInit()
中的 subscribe
将 debounce
1 秒,如下面的代码.
searchTextChanged = new Subject();构造函数(私有 http:Http){}ngOnInit(): 无效 {this.subscription = this.searchTextChanged.去抖动时间(1000).distinctUntilChanged().mergeMap(search => this.getValues()).subscribe(() => { });}获取值(){return this.http.get("https://www.example.com/search/?q="+this.q).地图((res:响应) =>{const studentResult = res.json();控制台日志(学生结果);如果(学生结果.成功){this.results = studentResult.data;} 别的 {this.results = [];}})}搜索($事件){this.searchTextChanged.next($event.target.value);}
rxjs v6 有几个重大变化,包括简化操作符的导入点.尝试安装 rxjs-compat
,它会添加回这些导入路径,直到代码迁移完毕.
从 RxJS
导入必要的操作符.下面是 RxJS 5.x
import { Subject } from "rxjs/Subject";导入rxjs/add/operator/debounceTime";导入rxjs/add/operator/distinctUntilChanged";import { Observable } from "rxjs/Observable";导入rxjs/add/operator/mergeMap";
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 = [];
}
}
)
}
}
Screenshot
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
});
}
and this's also not work. Property 'fromEvent' does not exist on type 'typeof Observable'
Observable.fromEvent<KeyboardEvent>(this.getNativeElement(this.term), 'keyup')
So, what's the correct way to implement this ?
Thank you.
解决方案 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 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.
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天全站免登陆