问题
Im am implementing a search-field with async
in Anglur 5. When the user begins typing in the search-box, the loading-indicator should show up. And when the results have arrived, the indicator should be hidden.
I tried this approach, but then loading indicator is visible, even if the user has not typed anything. So what is the best way to implement this?
My Template:
<mdl-textfield #searchBox (keyup)="search(searchBox.value)" type="text" placeholder="Nach Kurs, Beteuer, Studiengruppe suchen..."></mdl-textfield>
<!--[...]-->
<div *ngIf="courses$ | async as courses">
<ng-container *ngIf="courses.length; else noItems">
<app-course *ngFor="let course of courses" [course]="course" [addAble]="true"></app-course>
</ng-container>
<ng-template #noItems><em>Kein Ergebniss für "{{searchBox.value}}"</em></ng-template>
</div>
The Component:
public courses$: Observable<Course[]>;
public searchCourseTerm = new Subject<string>();
public serachLoadingIndicator: boolean = false;
constructor(private courseService: CourseService) { }
gOnInit() {
this.courses$ = this.searchCourseTerm.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.courseService.searchCourse(term)),
);
}
search(term: string ){
this.searchCourseTerm.next(term);
}
回答1:
ngOnInit() {
this.courses$ = this.searchCourseTerm.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => this.searching = true)
switchMap((term: string) => this.courseService.searchCourse(term)),
tap(() => this.searching = false)
);
}
should do the trick.
来源:https://stackoverflow.com/questions/49609228/angular-5-search-with-async-pipe-show-loading-indicator