如何初始化搜索调用?

How to initialize a search call?

我有一个主要由文本框(输入)和结果显示区域组成的组件:

<div class="row search">
  <div class="col">
    <input
      id="iptSearch"
      type="text"
      class="form-control"
      placeholder="search blueprints"
      (keyup)="keyUp$.next($event.target.value)"
    />
  </div>
</div>

<ng-container *ngIf="courses$ | async as courses; else loadingCourses">

  <table class="table table-borderless table-responsive-sm">
    <tbody>
      <tr *ngFor="let item of courses | slice: (page-1) * pageSize : (page-1) * pageSize + pageSize">
        <ew-browse-courses [course]=item></ew-browse-courses>
      </tr>
    </tbody>
  </table>

  <ngb-pagination
    [(page)]="page"
    [pageSize]="pageSize"
    [collectionSize]="courses.length">
  </ngb-pagination>

</ng-container>

<ng-template #loadingCourses>
  <div class="spinner-border"></div>
</ng-template>

在组件中,我使用一个主题和一个服务(都是可观察的)来获取搜索文本并将其发送到服务:

import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

import { CourseBrowse } from '../_models/course';
import { CourseService } from '../_services/course.service';

@Component({
  selector: 'ew-course-home',
  templateUrl: './course-home.component.html',
  styleUrls: ['./course-home.component.css']
})
export class CourseHomeComponent implements OnInit {
  courses$: Observable<CourseBrowse[]>;
  keyUp$ = new Subject<string>();

  // pagination
  pageSize = 5;
  page = 1;

  constructor(private courseService: CourseService) { }

  ngOnInit(): void {
  
   // that was another attempt (mimic an "onkeyup")
   // const element: HTMLElement = document.getElementById('iptSearch') as HTMLElement;
   // element.onkeyup; // that's a property of course - there's no method like "keypress"

    this.courses$ = this.keyUp$.pipe(
      // filter(term => term.length >= 3),
      debounceTime(500),
      distinctUntilChanged(),
      switchMap(searchTerm => this.courseService.searchCourses(searchTerm))
    );

    this.keyUp$.next(''); // my ideas was to just send and empty string
  }
}

搜索本身工作正常,我的问题是我无法启动它。如果显示组件,它只会等待输入...

如果用户聚焦输入框并按回车键(搜索空字符串)服务 returns 整个列表(限制为 50 个)按预期进行。

所以我现在要做的是将空字符串发送到主题以首先执行此搜索。我使用 keyUp$.next('') 的方法没有用。我做错了什么?

提前致谢

您可以尝试使用 startWith 运算符

this.courses$ = this.keyUp$.pipe(
      startWith(''),
      // filter(term => term.length >= 3),
      debounceTime(500),
      distinctUntilChanged(),
      switchMap(searchTerm => this.courseService.searchCourses(searchTerm))
    );