如何在搜索键上实现去抖时间
How to implement debounce time on search key up
我正在我的应用程序中实现搜索功能我想在按键时实现去抖动时间。谁能帮我解决这个问题
HTML
<div class="mt-4">
<div class="form-group has-search">
<span class="fa fa-search form-control-feedback"></span>
<input type="search" class="form-control" [(ngModel)]="searchKeywords" (keyup)="getSmartSearchValues(searchKeywords)" (search)="clearSearch()" placeholder="Search here">
</div>
</div>
我试过了,但是显示错误
searchTextChanged = new Subject<string>();
ngOnInit(): void {
this.subscription = this.searchTextChanged
.debounceTime(1000)
.distinctUntilChanged()
.mergeMap(search => this.getSmartSearchValues('', ''))
.subscribe(() => { });
this.getAllData();
if (this.CoffeeItemList.length === 0) {
this.empty = true;
}
this.getItemsCount('');
}
错误
Property 'debounceTime' does not exist on type 'Subject<string>'.
Property 'subscription' does not exist on type 'AppComponent'
您可以将 debounceTime
添加到您的 FormControl。
例如:
...
Component({
selector: 'my-app',
template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
firstNameControl = new FormControl();
formCtrlSub: Subscription;
ngOnInit() {
// debounce keystroke events
this.formCtrlSub = this.firstNameControl.valueChanges
.debounceTime(1000)
.subscribe(newValue => this.firstName = newValue);
...
或者你可以使用fromEvent
export class HelloComponent implements OnInit, OnDestroy {
@Input() name: string;
@ViewChild("editor") editor: ElementRef;
subscription: Subscription;
ngOnInit() {
this.subscription = fromEvent(this.editor.nativeElement, "keyup").pipe(
map(event => this.editor.nativeElement.value),
debounceTime(1000)
).subscribe(val => this.name = val);
}
<form>
<input type="text" #editor name="hello">
</form>
见附件Stackblitz
或者 你将你的 ngModelChange
绑定到一个 Observable 并使用 debounceTime
:
<hello name="{{ name }}"></hello>
<input class="form-control" [(ngModel)]="userQuestion"
type="text" name="userQuestion" id="userQuestions"
(ngModelChange)="this.userQuestionUpdate.next($event)">
<ul>
<li *ngFor="let message of consoleMessages">{{message}}</li>
</ul>
export class AppComponent {
name = 'Angular 6';
public consoleMessages: string[] = [];
public userQuestion: string;
userQuestionUpdate = new Subject<string>();
constructor() {
// Debounce search.
this.userQuestionUpdate.pipe(
debounceTime(400),
distinctUntilChanged())
.subscribe(value => {
this.consoleMessages.push(value);
});
}
}
参见 Stackblitz2
编辑:
此外,您可以在 Angular 的 Practical observable usage 官方文档中找到示例(其中使用了 debounceTime
)。
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
const searchBox = document.getElementById('search-box');
const typeahead = fromEvent(searchBox, 'input').pipe(
map((e: KeyboardEvent) => (e.target as HTMLInputElement).value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged(),
switchMap(() => ajax('/api/endpoint'))
);
typeahead.subscribe(data => {
// Handle the data from the API
});
您正在寻找这样的东西吗?
参见 this link
export class AppComponent implements OnInit {
@ViewChild('searchKeywords') searchKeywords: ElementRef;
constructor(private httpClient: HttpClient) {}
ngOnInit() {
fromEvent(this.searchKeywords.nativeElement, 'keyup').pipe(
// get value
map((event: any) => event.target.value)
// if character length greater then 2
,filter(res => res.length > 2)
// Time in milliseconds between key events
,debounceTime(500)
// If previous query is diffent from current
,distinctUntilChanged()
,switchMapTo(this.http.get<any>('...'))
// subscription for response
).subscribe(res => {
console.log(res);
});
}
}
我正在我的应用程序中实现搜索功能我想在按键时实现去抖动时间。谁能帮我解决这个问题
HTML
<div class="mt-4">
<div class="form-group has-search">
<span class="fa fa-search form-control-feedback"></span>
<input type="search" class="form-control" [(ngModel)]="searchKeywords" (keyup)="getSmartSearchValues(searchKeywords)" (search)="clearSearch()" placeholder="Search here">
</div>
</div>
我试过了,但是显示错误
searchTextChanged = new Subject<string>();
ngOnInit(): void {
this.subscription = this.searchTextChanged
.debounceTime(1000)
.distinctUntilChanged()
.mergeMap(search => this.getSmartSearchValues('', ''))
.subscribe(() => { });
this.getAllData();
if (this.CoffeeItemList.length === 0) {
this.empty = true;
}
this.getItemsCount('');
}
错误
Property 'debounceTime' does not exist on type 'Subject<string>'.
Property 'subscription' does not exist on type 'AppComponent'
您可以将 debounceTime
添加到您的 FormControl。
例如:
...
Component({
selector: 'my-app',
template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
firstNameControl = new FormControl();
formCtrlSub: Subscription;
ngOnInit() {
// debounce keystroke events
this.formCtrlSub = this.firstNameControl.valueChanges
.debounceTime(1000)
.subscribe(newValue => this.firstName = newValue);
...
或者你可以使用fromEvent
export class HelloComponent implements OnInit, OnDestroy {
@Input() name: string;
@ViewChild("editor") editor: ElementRef;
subscription: Subscription;
ngOnInit() {
this.subscription = fromEvent(this.editor.nativeElement, "keyup").pipe(
map(event => this.editor.nativeElement.value),
debounceTime(1000)
).subscribe(val => this.name = val);
}
<form>
<input type="text" #editor name="hello">
</form>
见附件Stackblitz
或者 你将你的 ngModelChange
绑定到一个 Observable 并使用 debounceTime
:
<hello name="{{ name }}"></hello>
<input class="form-control" [(ngModel)]="userQuestion"
type="text" name="userQuestion" id="userQuestions"
(ngModelChange)="this.userQuestionUpdate.next($event)">
<ul>
<li *ngFor="let message of consoleMessages">{{message}}</li>
</ul>
export class AppComponent {
name = 'Angular 6';
public consoleMessages: string[] = [];
public userQuestion: string;
userQuestionUpdate = new Subject<string>();
constructor() {
// Debounce search.
this.userQuestionUpdate.pipe(
debounceTime(400),
distinctUntilChanged())
.subscribe(value => {
this.consoleMessages.push(value);
});
}
}
参见 Stackblitz2
编辑:
此外,您可以在 Angular 的 Practical observable usage 官方文档中找到示例(其中使用了 debounceTime
)。
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
const searchBox = document.getElementById('search-box');
const typeahead = fromEvent(searchBox, 'input').pipe(
map((e: KeyboardEvent) => (e.target as HTMLInputElement).value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged(),
switchMap(() => ajax('/api/endpoint'))
);
typeahead.subscribe(data => {
// Handle the data from the API
});
您正在寻找这样的东西吗? 参见 this link
export class AppComponent implements OnInit {
@ViewChild('searchKeywords') searchKeywords: ElementRef;
constructor(private httpClient: HttpClient) {}
ngOnInit() {
fromEvent(this.searchKeywords.nativeElement, 'keyup').pipe(
// get value
map((event: any) => event.target.value)
// if character length greater then 2
,filter(res => res.length > 2)
// Time in milliseconds between key events
,debounceTime(500)
// If previous query is diffent from current
,distinctUntilChanged()
,switchMapTo(this.http.get<any>('...'))
// subscription for response
).subscribe(res => {
console.log(res);
});
}
}