【问题标题】:Angular 12/rxjs: BehaviorSubject shall return empty object array, but returns undefined insteadAngular 12/rxjs:BehaviorSubject 应返回空对象数组,但返回未定义
【发布时间】:2022-01-16 22:21:19
【问题描述】:

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

  • 没有用户输入(如果 observable = 未定义)
  • 未找到结果(如果 observable = 空数组)
  • 找到的结果(如果 observable = 非空数组)

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



  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([]);
        }
      })
    );
  }


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

如何正确执行以下操作之一:

  • of([]) 识别为空数组
  • 将另一个可观察对象作为空数组返回
  • 或用不同的方法完全确定这三个场景。

谢谢

【问题讨论】:

  • 您似乎正试图从tap 中返回。该回报将被忽略。也许你想要map
  • tap() 返回一个值不会改变next 的值。也许你想使用map())然后你不需要of())或switchMap()

标签: angular typescript rxjs


【解决方案1】:

您想使用 map 而不是 tap 从 getLocations 返回值。 ma​​p 运算符转换发出的值,而 tap 执行副作用。您还可以使用 nullish 合并运算符 (??) 而不是使用 if 语句来使您的代码更紧凑。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    相关资源
    最近更新 更多