Issue
I have a livesearch and want to understand three scenarios:
- no user input (if observable = undefined)
- no result found (if observable = empty array)
- results found (if observable = non-empty array)
The trouble is my behaviour subject which holds the resultset recognizes 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); //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([]);
}
})
);
}
So whenever I return of([]) in hope to return an empty array, I always receive an "undefined" value.
How can I correctly do one of the following:
- recognize
of([])as empty array - return another observable as empty array
- or determine the three scenarios with a different approach altogether.
Thanks
Solution
You wanted use map instead of tap to return values from getLocations. The map operator transforms the emitted value, while tap performs a side-effect. Also you can use the nullish coalescing operator (??) instead of using an if statement to make your code a little more compact.
fetchLocation(incSearchTerm: string): Observable<SearchResult[] | undefined> {
if (!incSearchTerm) {
return of(undefined);
}
return this.httpHandler.getLocations(incSearchTerm).pipe(
map(searchResults => searchResults ?? [])
);
}
Answered By - Daniel Gimenez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.