จากการค้นหาในบทช่วยสอนฮีโร่ของ angular.io ฉันได้สร้างการค้นหาสัตว์อย่างง่ายโดยใช้สิ่งที่สังเกตได้ ทุกอย่างทำงานได้ดี แต่ตอนนี้ฉันต้องการล้างค่าในการค้นหา และล้างรายการผลลัพธ์เมื่อฉันเลือกผลลัพธ์
ฉันได้สร้างวิธีการล้างค่าอินพุตเมื่อคลิกลิงก์ โดยคาดหวังว่าสิ่งที่สังเกตได้จะอัปเดตและล้าง แต่น่าเสียดายที่มันไม่เกิดขึ้น และรายการแบบเลื่อนลงยังคงอยู่ ฉันได้ลองกำหนดสิ่งที่สังเกตได้ใหม่ซึ่งใช้งานได้ แต่สิ่งที่สังเกตได้นั้นถูกยกเลิกการสมัคร ซึ่งเป็นสิ่งที่ฉันไม่ต้องการทำ
ฉันแน่ใจว่านี่เป็นกรณีของฉันที่ยังไม่เข้าใจวิธีการทำงานกับสิ่งที่สังเกตได้อย่างสมบูรณ์ ดังนั้นหวังว่าพวกคุณจะช่วยฉันได้
ขอบคุณ นี่คือรหัสของฉัน
import { Component, OnInit } from '@angular/core';
import {Observable, Subject} from 'rxjs'
import {
debounceTime, distinctUntilChanged, switchMap
} from 'rxjs/operators';
import { AnimalService } from '../services/animal.service';
import { Animal } from '../models/animal';
@Component({
selector: 'app-animal-search',
templateUrl: './animal-search.component.html',
styleUrls: ['./animal-search.component.css']
})
export class AnimalSearchComponent implements OnInit {
animals$: Observable<Animal[]>;
private searchTerms = new Subject<string>();
private searchTerm: string;
constructor(private animalService: AnimalService) { }
search(term: string):void {
this.searchTerms.next(term);
}
ngOnInit() {
this.animals$ = this.searchTerms.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.animalService.searchAnimals(term)),
);
this.animals$.subscribe( )
}
clearSearch()
{
//PART THAT ISNT WORKING
this.searchTerm = "";
this.searchTerms = new Subject<string>();
}
}
<div id="search-component" class="search-component-container">
<input #searchBox id="search-box" [(ngModel)]="searchTerm" (keyup)="search(searchBox.value)" class="search-component-input" />
<ul class="search-result">
<li *ngFor="let animal of animals$ | async" >
<a routerLink="/animal/{{animal.id}}" (click)="clearSearch()">
{{animal.Name}}
</a>
</li>
</ul>
</div>