1
我需要擺脫搜索結果中的重複值。 請幫助我找到一個簡單的解決方案。擺脫搜索結果中的重複值/ angular2/typescript/js
我買方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[]);
}
}
我買方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[]>([]);
});
}
}
和查看,與買方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>
你應該注意到,'r.json()的數據作爲買家[]);'不會產生類型對象的陣列。它仍然只會返回一個對象字面值。 **類型斷言不是類型轉換**。這意味着任何類方法/屬性訪問器都不會在這些對象上可用。 – Fiddles