当流预期有角度时,您提供了未定义

Med*_*fsa 1 stream undefined rxjs angular

我正在尝试创建一个自动完成功能,为每次输入从 API 接收数据,现在我每次都会显示数据,但首先我总是在每种类型上出现此错误。

您在需要流的地方提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。

即使我将数据订阅到变量中,也没有任何反应。这是错误的图像,您将看到显示的数据在此输入图像描述

这是我的 app.component.ts

ngOnInit() {
    this.results = this.searchText.valueChanges.pipe(
      startWith(''),
      // delay emits
      debounceTime(300),
      switchMap(value => {
        if (value !== '' && value !== undefined) {
           this.lookup(value).subscribe((value: any) => {
             console.log('data sub:', value);
           });
        } else {
          return of(null);
        }
      })
    );
  } 

lookup(value: string): Observable<any> {
    return this.appService.autoComplete(value.toLowerCase()).pipe(
      map(results => results.hits.hits)
    );
  }

Run Code Online (Sandbox Code Playgroud)

这是我的服务。ts

  public autoComplete(name: string): Observable<Response> {


    const params = new HttpParams()
        .set('name', name);
    return this.httpClient.get<Response>(this.host, { params});
}
Run Code Online (Sandbox Code Playgroud)

这也是我的 html:

 <input type="text" matInput   [matAutocomplete]="auto"
                [formControl]="searchText" >
                <mat-autocomplete #auto="matAutocomplete" >
                  <mat-option *ngFor="let item of results | async " [value]="item._source.firstname">
                    {{item._source.firstname}}
                  </mat-option>
                </mat-autocomplete>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l D 7

您不应该在switchMap运营商内部订阅。它的目的是从一个可观察值切换到另一个可观察值。因此它本质上应该返回可观察的结果,并且订阅必须位于运算符链的末尾。在您的情况下,订阅是通过async模板中的管道完成的。

ngOnInit() {
  this.results = this.searchText.valueChanges.pipe(
    startWith(''),
    debounceTime(300),    // delay emits
    switchMap(value => {
      if (value !== '' && value !== undefined) {
        return this.lookup(value);      // <-- return `this.lookup()` here
      } else {
        return of(null);
      }
    })
  );
}
Run Code Online (Sandbox Code Playgroud)

其他生活质量变化:

  1. 使用双联运算符!!检查变量有效性。空字符串''假的
  2. 使用 RxJSiif有条件地返回可观察值。
  3. 使用 RxJSNEVER常量而不是of(null).
ngOnInit() {
  this.results = this.searchText.valueChanges.pipe(
    startWith(''),
    debounceTime(300),    // delay emits
    switchMap(value =>
      iif(
        () => !!value,
        this.lookup(value),
        NEVER
      )
    )
  );
}
Run Code Online (Sandbox Code Playgroud)