2
我正在使用角度2和最新的路由器組件來實現搜索功能。當我第一次點擊搜索按鈕時,路由器導航到搜索組件並從服務中檢索數據。之後,當我更改搜索文本數據不會更改,但查詢參數更改。組件不會重新啓動查詢參數更改角度2
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;
});
}
}
我現在應該怎麼辦?請幫忙。提前致謝。
謝謝。有用 :) – Shuvo