I am currently developing a personal app and facing an issue with retrieving user data when initializing my component for the first time. It seems that my searchTerms
are causing an obstacle in processing the subject string properly. I have attempted using this.searchTerms.next('');
in the ngOnInit
method but it did not work as expected. Interestingly, if I enter a user name and then delete it, the list of users appears due to the execution of the else block for switchMap
.
Overview of My Component:
export class UserComponent implements OnInit {
users: Observable<User[]>;
private searchTerms = new Subject<string>();
getUsers(): void {
this.users = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time the term changes
// return the http search observable
? this.userService.search(term)
// or the observable of all users if there was no search term
: this.userService.search(''))
.catch(() => {
return Observable.of<User[]>([]);
});
}
ngOnInit(): void {
this.getUsers();
}
search(term: string): void {
// Push a search term into the observable stream.
this.searchTerms.next(term);
}
My Template Structure:
...
<h4>User Search</h4>
<input #userSearchBox id="user-search-box" (keyup)="search(userSearchBox.value)" />
...
<div *ngFor="let user of users | async" class="input-group">
...