【发布时间】: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