I have implemented a search field within my top-bar component
and I am facing an issue in passing the input value of that search field to another component.
Design
- Search service
- Top bar component
- Result component
Operation
Top bar component
receives the input value and forwards it to theSearch service
Result component
retrieves the input value from theSearch service
for further processing
Current Status
- Successfully obtaining the input value in
Top bar component
- Unable to retrieve any value in
Result component
Code Snippets
TopBar component
// HTML
<input nz-input nzBorderless placeholder="Search here..." (keydown.enter)="onInput($event)" style="background-color: #F3F6FC;" />
// SCRIPT
import { SearchServiceService } from 'src/app/services/search/search-service.service';
@Input() searchName: string;
constructor(
private globalSearchService: SearchServiceService,
) {}
public onInput(event: any){
// this pushes the input value into the service's Observable.
this.globalSearchService.searchTerm.next(event.target.value);
}
Search service
export class SearchServiceService {
public searchTerm: BehaviorSubject<string> = new BehaviorSubject<string>(null);
constructor() { }
}
Result component
import { SearchServiceService } from 'src/app/services/search/search-service.service';
public searchTerm: string = "";
constructor(
private globalSearchService: SearchServiceService
) { }
ngOnInit(): void {
// this listens to the input value from the service and does something on change.
this.globalSearchService.searchTerm.subscribe((newValue: string) => {
console.log('search newValue :', newValue); // Nothing prints here!
// this is where you would apply your existing filtering.
this.searchTerm = newValue;
});
}
Any suggestions?
Update
Q: How did I register my search service?
A:
import { SearchServiceService } from 'src/app/services/search/search-service.service';
const MODULES = [CommonModule, RouterModule, AntdModule, TranslateModule, InfiniteScrollModule, FormsModule, ReactiveFormsModule]
@NgModule({
imports: [...MODULES],
declarations: [ACLComponent],
exports: [...MODULES],
providers: [SearchServiceService],
})
export class SharedModule {}