当输入不为空且延迟输入完成时进行搜索

时间:2017-12-15 20:15:28

标签: angular2-forms angular2-services angular2-http

我想仅在用户输入不为空且有一些延迟时才调用服务,以便用户完成输入。

以下是代码。请帮忙。

Component.ts

searchByName(event) {

this.facilityService.searchFacilityName(event.target.value).subscribe(facilities => this.facilities = facilities); }

Service.ts

searchFacilityName(name) {
return this.http.get('http://localhost:8000/searchFacilityByName/' + name)
  .map((response:Response) => response.json())
  .catch(
    (error: Response) => {
        return Observable.throw('Something went wrong. Please try again.')
    }
  );

}

2 个答案:

答案 0 :(得分:2)

这会有所帮助,

 this.testForm.controls.searchText.valueChanges.subscribe(x=>{
  if(this.testForm.controls.searchText.dirty && this.testForm.controls.searchText.valid) {
    setTimeout(function(){
      this.searchFacilityName(this.testForm.controls.searchText.value)
    },3000);
  } });

答案 1 :(得分:0)

您需要首先指定时间限制,即您希望在上次键入事件之后等待的时间,以确保用户已停止输入。 之后你可以试试这个

<input type='text' [ngModel]='userInput' (keyup)='checkTimeLimit()' (keydown)='typeCheck = typeCheck + 1'>

在您的组件中:

typeCheck = 0;
userInput;
timeLimit = 5000; // It is the time limit after which you consider that user has stopped typing (5s)

checkTimeLimit() {
  const temp = this.typeCheck;
  setTimeout(() => {
    if (temp === this.typeCheck) {  // It checks whether the user has pressed another key before the specified time limit
      this.typeCheck = 0;
      this.searchFacilityName(userInput);
    }
  }, this.timeLimit);
}