Angular 2:在另一个组件中显示搜索结果

时间:2017-06-28 04:01:16

标签: angular search methods angular2-components angular-template

我的搜索字段位于单独的组件上。在搜索时在建议列表上显示名称没有问题,因为我没有在不同的组件中显示它们。

  

搜索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中放置什么,以便结果显示在List Component中?

  

SearchService

getSuggestion(name:string): Observable<any> {
        return this.http
        .get(this.serverUrl + 'name/' + name)
        .map(this.extractData)
        .catch(this.handleError);
}

1 个答案:

答案 0 :(得分:3)

在SearchService中拥有主题。有主题,你不需要告诉其他组件新的结果。只要有结果,视图就会自动更新。

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     public results = 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,我们将知道是否进行了搜索调用。如果结果不为null但为空,我们将知道搜索结果为空。