I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have noticed that when I change the search text, the data does not update but the query parameter changes.
navbar.component.ts
@Component({
selector:'navbar',
template:`
<div class="input-group">
<input type="text" class="form-control" placeholder="Search"
name="srch-term" id="srch-term" [(ngModel)] = "search_text">
<div class="input-group-btn">
<button class="btn btn-default" (click)="search()">
<i class="fa fa-search"></i>
</button>
</div>
</div>`,
styleUrls:['app/navbar/navbar.component.css'],
directives:[LoginComponent,SignupComponent,ROUTER_DIRECTIVES]
})
export class NavbarComponent {
State: NavbarState = "PUBLIC";
profileNavElement: NavbarElement;
userNameString: string;
search_text : string = '';
search(){
console.log(this.search_text);
if(this.search_text){
this.router.navigate(["/search"],{
queryParams:{query:this.search_text}
});
}
}
serach.component.ts
import { Component, OnInit, DoCheck } from '@angular/core';
import { ActivatedRoute,Router,ROUTER_DIRECTIVES} from '@angular/router';
import { SearchService } from './search.service';
import {Location} from '@angular/common';
@Component({
moduleId: module.id,
selector: 'search',
templateUrl: 'search.component.html',
styleUrls:['./search.component.css'],
providers:[ROUTER_DIRECTIVES,SearchService]
})
export class SearchComponent implements OnInit {
query:string = '';
videos:Object[] ;
resultFound:boolean=false ;
resultNotFound:boolean=false;
constructor(private route:ActivatedRoute,
private router:Router,
private _searchService:SearchService) {
}
ngOnInit() {
this.router.routerState
.queryParams
.subscribe(data => {
this.query = data['query'];
});
this.getSearchResult();
}
getSearchResult(){
this._searchService.getSearchResult(this.query)
.subscribe((result) => {
this.resultFound = true;
this.resultNotFound = false;
this.videos = result;
},
(error) => {
this.resultFound = false;
this.resultNotFound = true;
});
}
}
Any suggestions on how to address this issue? Your help is greatly appreciated. Thank you in advance.