ค้นหาเว็บไซต์

javascript - วิธีเพิ่มเวลา debounce ให้กับช่องค้นหา input ใน typescript?


ฉันจะเพิ่มเวลา debounce ให้กับช่องค้นหาแบบไดนามิกที่ค้นหาข้อมูลในตารางข้อมูลได้อย่างไร? ฉันได้ดูวิธีแก้ปัญหาบางอย่างบนเว็บไซต์แล้ว แต่โค้ดของฉันแตกต่างเล็กน้อย ฉันไม่ได้ใช้ throttle หรือสิ่งอื่นใดเลย ดังนั้นฉันจึงสับสน

โค้ดเทมเพลตของฉัน:

<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search element">

และ TypeScript สำหรับสิ่งนั้นคือ:

applyFilter(filterValue: string) {
    this.tableDataSource.filter = filterValue.trim().toLowerCase();
}

ฉันต้องการเพิ่มเวลาหน่วงเพื่อให้การค้นหาจะเกิดขึ้นทุก 2 วินาทีและไม่ส่งคำขอจำนวนมากสำหรับทุกการเปลี่ยนแปลง

ขอบคุณล่วงหน้า

ฉันได้พยายามเรียกใช้เมทอดจากเมทอดอื่นด้วย pipe

filterData(filterValue: string) {
    this.applyFilter(filterValue).pipe(debounceTime(2000))
}

แต่ตอนนี้มันบอกว่า, pipe ไม่ปรากฏบนชนิด void

คำตอบ #1

แม่แบบ :

<input matInput (input)="terms$.next($event.target.value)" type="text" 
  placeholder="Search element">

ส่วนประกอบ :

private terms$ = new Subject<string>();

ngOnInit () {
  this.terms$.pipe(
    debounceTime(400), // discard emitted values that take less than the specified time between output
    distinctUntilChanged() // only emit when value has changed
  ).subscribe(term => {
    // do your search with the term
  });
}

คำตอบ #2

คุณกำลังใช้ตัวดำเนินการ pipe กับสตริง คุณสามารถใช้ pipe กับ Observable ได้เท่านั้น ดังนั้นคุณควรสร้าง Subject ในคอมโพเนนต์ของคุณ Subject ใน RxJS ทำหน้าที่ทั้งเป็น Observable และ Observer กล่าวอีกนัยหนึ่ง มันสามารถปล่อยค่าออกมาและฟังค่านั้นเมื่อค่ามีการเปลี่ยนแปลง

private searchSub$ = new Subject<string>();

applyFilter(filterValue: string) {
    this.searchSub$.next(filterValue)
}

ngOnInit() {
   this.searchSub$.pipe(
     debounceTime(400),
     distinctUntilChanged()
   ).subscribe((filterValue: string) => {
     this.tableDataSource.filter = filterValue.trim().toLowerCase();
   });
}

เมื่อเมธอด applyFilter() ถูกเรียกใช้ในทุก ๆ การกดปุ่ม Subject จะส่งค่า filterValue ออกมา ใน ngOnInit() ของคุณ คุณควรฟัง/สมัครสมาชิกกับ Subject ของคุณ ดังนั้นคุณสามารถใช้ตัวดำเนินการ pipe และ debounceTime ได้

บทความที่เกี่ยวข้อง