I'm facing an issue while trying to incorporate a search bar with autocomplete suggestions in Angular 9. It worked perfectly in the tour of heroes tutorial, but when I attempt to replicate it, the searchTerms pipe seems to be inactive (the service is not being called).
Upon inspecting the observers of searchTerms in the tour of heroes app, I noticed that it already has one observer immediately after creation. However, in my own App, this is not the case. This leads me to wonder: at what point does the searchTerms in the tour of heroes App receive its observer?
This implementation works as expected, and the service is invoked
import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {
debounceTime, distinctUntilChanged, switchMap
} from 'rxjs/operators';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ]
})
export class HeroSearchComponent implements OnInit {
heroes$: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(private heroService: HeroService) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
// One observer exists
console.log(this.searchTerms.observers);
this.heroes$ = this.searchTerms.pipe(
// Wait for 300ms after each keystroke before processing the term
debounceTime(300),
// Ignore if the new term is the same as the previous one
distinctUntilChanged(),
// Switch to a new search observable each time the term changes
switchMap((term: string) => this.heroService.searchHeroes(term)),
);
}
}
This implementation does not work as expected
import {Component, OnInit} from '@angular/core';
import {Observable, Subject} from "rxjs";
import {SearchService} from "../search.service";
import {debounceTime, distinctUntilChanged, switchMap} from "rxjs/operators";
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
suggestions$: Observable<string[]>;
private searchTerms = new Subject<string>();
constructor(private searchService: SearchService) {}
search(value: string): void {
this.searchTerms.next(value);
}
ngOnInit(): void {
// No observers found, service from the pipe is not triggered
console.log(this.searchTerms.observers);
this.suggestions$ = this.searchTerms.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.searchService.getSuggestions(term)),
);
}
}