Exploring different scenarios with a livesearch functionality:
- No user input (observable = undefined)
- No results found (observable = empty array)
- Results found (observable = non-empty array)
The issue lies in how my behavior subject interprets an empty array as "undefined".
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); //returns undefined for an empty array `of([])` ;((
this.loc$.next(locations);
});
}
searchLocation(incSearchTerm: string): void {
this.searchLocation$.next(incSearchTerm);
}
fetchLocation(incSearchTerm: string): Observable<SearchResult[] | undefined> {
if (!incSearchTerm) {
// return undefined when there's no search term
return of(undefined);
}
return this.httpHandler.getLocations(incSearchTerm).pipe(
tap(searchResults => {
if (searchResults ) {
return searchResults ;
} else {
// attempting to return an empty array, however it is interpreted as undefined
return of([]);
}
})
);
}
Whenever I use of([])
hoping to get back an empty array, it always returns "undefined".
How can I address this issue by either:
- Recognizing
of([])
as an empty array - Returning a different observable that contains an empty array
- Or approaching the three scenarios differently.
Thank you