我需要摆脱搜索结果中的重复值。 请帮我找一个简单的解决方案。
我的 buyer-search.service.ts :
export class BuyerSearchService {
constructor(private http: Http) {}
search(term: string, atrib: string): Observable<Buyer[]> {
return this.http
.get(`app/buyers/?${atrib}=${term}`)
.map((r: Response) => r.json().data as Buyer[]);
}
}
我的 buyer-search.component.ts
export class BuyerSearchComponent implements OnInit {
buyers: Observable<Buyer[]>;
private searchTerms = new Subject<string>();
constructor(
private buyerSearchService: BuyerSearchService,
private router: Router) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.buyers = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time
// return the http search observable
? this.buyerSearchService.search(term, 'clientName')
// or the observable of empty buyers if no search term
: Observable.of<Buyer[]>([]))
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Buyer[]>([]);
});
}
}
和查看, buyer-search.component.html :
<div id="search-component">
<input #searchBox id="search-box" (keyup)="search(searchBox.value)"/>
<div id="buyerByNameResults">
<div *ngFor="let buyer of buyers | async"
class="search-result">
<p class="buyer-name-s">{{buyer.clientName}}</p>
</div>
</div>
</div>
答案 0 :(得分:0)
也许您需要在内部observable上执行.distinct(),并将键选择器传递给第一个参数。
this.buyerSearchService
.search(term, 'clientName')
.distinct(function (x) { return x.clientName; });
如果需要,还有第二个参数允许您提供比较器。
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/distinct.md