I am trying to implement a search bar which is included in a nav bar, and routing is imposted this way, app.component.html has the router-outlet, while the bootstrap nav bar component is called in the other html components, so that the login page will be displayed first without the nav bar. But, the search bar does not give me back the results I want, in short if I want to be able to use the search term, artist name, and have has a result the result page in this case the music-genre page displaying only the artist name I looked for on the search bar. So navigating on the already filtered data page.
Thanks for your help!
music-genre ts
musicData: any;
searchTerm: string = '';
searchResults: any[] = [];
ngOnInit(): void {
this.fetchData();
this.searchService.searchTerm$.subscribe(term => {
this.searchTerm = term;
this.filterData(this.searchTerm);
});
this.route.paramMap.subscribe((params: ParamMap) => {
this.searchTerm = params.get('term') || '';
this.filterData(this.searchTerm);
});
}
filterData(term: string): void {
if (!term || !this.musicData) {
this.filteredData = [];
} else {
this.filteredData = this.musicData.filter((artist: { name: string; }) =>
artist.name.toLowerCase().includes(term.toLowerCase())
);
}
}
searchService
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SearchService {
private searchTermSubject: BehaviorSubject<string> = new BehaviorSubject<string>('');
constructor() { }
get searchTerm$(): Observable<string> {
return this.searchTermSubject.asObservable();
}
setSearchTerm(term: string): void {
this.searchTermSubject.next(term);
}
}
NavBarComponent
search() {
console.log("Search term:", this.searchTerm);
this.searchService.setSearchTerm(this.searchTerm);
this.router.navigate(['/music-genre', { term: this.searchTerm }]);
}