Angular 4搜索结果清晰

时间:2017-09-21 16:35:55

标签: angular rxjs

我使用下面的代码为我的组件提供异步搜索功能。搜索完成后,如何清除组件中方法的结果?将searchResults设置为空数组意味着它不再是搜索结果数组,因此搜索不再有效。选择后,我需要清除结果并允许用户再次搜索。

searchResults: Observable<any>;
this.searchResults = 
      this.form.controls['search'].valueChanges
        .debounceTime(200)
        .switchMap(query => this.search.searchPeople(query));

这是模板代码:

<md-input-container style="width:500px">
   <input mdInput formControlName="search" placeholder="Search Name" />
 </md-input-container>

      <div *ngFor="let person of searchResults | async">
        <p><button md-raised-button color="primary" 
          (click)="selectPerson(person)">
          Select</button> {{person.firstName}}</p>
        <p><img [src]="person.photo.url"/></p>
        <hr/>
       </div>

搜索方法:

searchPeople(query){
    return this.http.get(`${BASE_URL}?q=${query}`)
      .map((res:Response) => res.json())
      .map(json => json.items);
  }

1 个答案:

答案 0 :(得分:1)

您可以将搜索结果与将清除结果的主题合并:

clearSearch = new Subject();
searchResults: Observable<any>;

...

this.searchResults = this.form.controls['search'].valueChanges
    .debounceTime(200)
    .switchMap(query => this.search.searchPeople(query))
    .merge(this.clearSearch.mapTo([]));

然后清除结果只需调用:

this.clearSearch.next();