Angular 12/rxjs:BehaviorSubject 应 return 空对象数组,但 return 未定义

Angular 12/rxjs: BehaviorSubject shall return empty object array, but returns undefined instead

我有livesearch,想了解三个场景:

问题是保存结果集的我的行为主体将空数组识别为“未定义”。



  loc$ = new BehaviorSubject<SearchResult[] | undefined>(undefined);
  searchLocation$ = new BehaviorSubject<string>("");

  initModule(): void {
    this.searchLocation$.pipe(
      switchMap((searchTerm: string) => this.fetchLocation(searchTerm)),
    ).subscribe(locations => {
      console.log(locations); //undefined if empty array `of([])` returned!! ;((
      this.loc$.next(locations);
    });

  }

  searchLocation(incSearchTerm: string): void {
    this.searchLocation$.next(incSearchTerm);
  }

  fetchLocation(incSearchTerm: string): Observable<SearchResult[] | undefined> {
    if (!incSearchTerm) {
      // if no search term, return undefined
      return of(undefined);
    }

    return this.httpHandler.getLocations(incSearchTerm).pipe(
      tap(searchResults => {
        if (searchResults ) {
          return searchResults ;
        } else {
          // if no results, return empty array -- this does not work
          return of([]);
        }
      })
    );
  }


所以每当我 return of([]) 希望 return 一个空数组时,我总是收到一个“未定义”值。

我怎样才能正确执行以下操作之一:

谢谢

您想使用 map 而不是 tap 从 getLocations 获取 return 值。 map 运算符转换发出的值,而 tap 执行副作用。您还可以使用无效合并运算符 (??) 而不是使用 if 语句来使您的代码更紧凑。

fetchLocation(incSearchTerm: string): Observable<SearchResult[] | undefined> {
  if (!incSearchTerm) {
    return of(undefined);
  }
  return this.httpHandler.getLocations(incSearchTerm).pipe(
    map(searchResults => searchResults ?? [])
  );
}