Angular 5: Search with Async Pipe - show loading indicator

孤人 提交于 2020-01-24 01:01:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!