我的搜索字段在单独的组件上。搜索时在建议列表上显示名称没有问题,因为我没有在不同的组件中显示它们。
搜索HTML
<input type="text" placeholder="Search" (keyup)="getSuggestion($event.target.value)">
<div class="suggestion" *ngIf="results.length > 0 && suggest === true">
<div *ngFor="let result of results" class="search-res" (click)="showEmployee(result._id)"> {{ result.name }} </div>
</div>
<div class="suggestion" *ngIf="results.length === 0 && suggest === true">
<div> No results found </div>
</div>
搜索组件
getSuggestion(name) {
$('.suggestion').show();
this.searchService
.getSuggestion(name)
.subscribe(
name => this.results = name,
error => alert(error),
);
}
但是,如果我想在change
事件上的其他组件(列表组件(中显示它怎么样?
在函数调用中我应该在输入字段中添加什么?我应该在searchComponent中放置什么,以便结果将显示在列表组件中?
searchService
getSuggestion(name:string): Observable<any> {
return this.http
.get(this.serverUrl + 'name/' + name)
.map(this.extractData)
.catch(this.handleError);
}
在您的搜索服务中有一个主题。就主题而言,您不需要告诉其他组件已经有了新的结果。一旦有结果,视图就会自动更新。
private results = new BehaviorSubject([]);
public getResults$(){
return this.results.asObservable();
}
public search(params){
//do search and add results to 'results'
this.results.next(response);
}
在您的列表组件中
constructor(private searchService: SearchService){
searchService.getResults$()
.subscribe(res){
this.results = res;
};
}
在您的html
中<div *ngIf="results.length>0" >
<!-- show results -->
</div>
您的情况的确切代码:
搜索组件html
<input type="text"
placeholder="Search"
(keyup)="getSuggestion($event.target.value)">
搜索组件TS
public getSuggestion(name){
this.searchService.getSuggestion(name);
}
搜索服务
private results = new BehaviorSubject([]);
public getResults$(){
return results.asObservable();
}
public getSuggestion(name:string) {
this.http
.get(this.serverUrl + 'name/' + name)
.map(this.extractData)
.subscribe(
response => this.results.next(response),
this.handleError
);
}
列表组件TS 公共结果= null;
constructor(private searchService: SearchService){
serachService.getResults$()
.subscribe(resultList: any[] => {
this.results = resultList;
});
}
列表组件html
<div class="suggestion"
*ngIf="results && results.length > 0 ">
<div *ngFor="let result of results"
class="search-res"
(click)="showEmployee(result._id)"
> {{ result.name }} </div>
</div>
<div class="suggestion"
*ngIf="results && results.length === 0 && suggest === true">
<div> No results found </div>
</div>
通过将结果设置为null,我们将知道是否有搜索呼叫。如果结果不是空的,而是空的,我们将知道搜索结果是空的。