我正在使用angular 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;
});
}
}
我现在该怎么办?请帮忙。提前谢谢。
答案 0 :(得分:3)
这是设计的。当只有路由参数改变时,组件将被重用。
您可以在getSearchResult()
内移动subscribe()
,以便每次参数更改时都会调用它:
ngOnInit() {
this.router.routerState
.queryParams
.subscribe(data => {
this.query = data['query'];
this.getSearchResult();
});
}
有计划支持自定义行为,但可能不会在最终之前。