我有一种情况,我想通过进行Http REST调用以获取匹配的字符串,将每次按键输入框中存在的字符串发送给服务器。但是它没有按我预期的那样工作,例如,假设输入框中的当前值为“ modul”,如果我在“ modul”之后输入字符“ e”,我希望该值传递给searchDepartmentsWithName
方法将是“模块”,但是它将给出当前值“模块”,而不是发送给服务器的修改后的值“模块”,并返回错误的匹配字符串。简而言之,传递给searchDepartmentsWithName方法的值始终是修改前的值。我们如何解决这个问题,或者这甚至是正确的做法?

searchnox.component.html

<body>
      <input type="text" placeholder="enter department name here.." (keypress)="searchDepartmentsWithName($event.target.value)" class="ticketinginput" />
      <div *ngFor="let department of searchResults; let i = index">
      <p id="result" href="#" (click)="onClick(department)">{{ department.departmentName }}</p>
      </div>
</body>


searchbox.component.ts

searchDepartmentsWithName(departmentName: string) {
this.serverService.searchDepartment(departmentName).subscribe( (response) => {
    console.log(response);
  },
  (error) => console.log(error)
);
this.prepareSearchResults();
}


server.service.ts

searchDepartment(name: string) {
 this.departmentList = new Array();
const url = `http://localhost:8082/request/searchDepartmentsByName/${name}`;
return this.http.get(url).map(
  (response: Response) => {
    const data = response.json();
    for (const temp of data) {
      console.log(temp);
        const department: IDepartment = <IDepartment> temp;
        this.departmentList.push(department);
        console.log('pushing department' + department.departmentName);
    }
    this.departmentListEventEmitter.emit(this.departmentList);
    console.log(this.departmentList.length);
  }
);
}

最佳答案

您应该使用keyup而不是keypress

(keyup)="searchDepartmentsWithName($event.target.value)"

09-25 15:58