我有一个输入,当用户键入它时,它执行实时搜索.例如,假设他搜索了以下内容:
car
结果将是:
[ { id: "1" name: "Ferrari" },{ id: "2" name: "Porsche" } ]
这个我能够成功,这是如何:
class WordComponent { word: Subject<string> = new Subject<string>(); result: any[] = []; constructor(private http: Http) { this.subscribe(); } subscribe(): void { this.word.debounceTime(400) .distinctUntilChanged() .switchMap((word: string): Observable<any[]> => this.http.get(word)) .subscribe((result: any[]): any[] => this.result = result); } search(event: any): void { this.word.next(event.target.value); } }
并且观点:
<input type="text" placeholder="Word" (keyup)="search($event)">
我希望用户能够同时键入多个单词并分别对每个单词进行实时搜索.例如,假设他搜索了以下内容:
car food sun
汽车的结果将是:
[ { id: "1" name: "Ferrari" },{ id: "2" name: "Porsche" } ]
食物的结果将是:
[ { id: "3" name: "egg" },{ id: "4" name: "cheese" } ]
太阳的结果将是:
[ { id: "5" name: "star" },{ id: "6" name: "sky" } ]
并且还合并每个单词的结果,在这种情况下它看起来像这样:
[ [{ id: "1" name: "Ferrari" },{ id: "2" name: "Porsche" } ],[{ id: "3" name: "egg" },{ id: "4" name: "cheese" } ],[{ id: "5" name: "star" },{ id: "6" name: "sky" } ] ]
但是,让我们说用户在输入所有单词并执行搜索后,希望更改其中一个.只需要重新搜索已更改的单词,并且必须重做最终结果的合并.
我仍然不知道rxjs的所有功能,我不知道实现这一目标的理想方法是什么.如果你想要一个参考,Display Purposes网站有一个非常相似的搜索引擎.
解决方法
我想你需要这样的东西:
subscribe(): void { this.word.debounceTime(400) .distinctUntilChanged() .switchMap((words: string): Observable<any[]> => Observable.forkJoin(words.split(' ').map(word => this.http.get(word))) ) .map(arrayWithArrays => [].concat(arrayWithArrays) .subscribe((result: any[]): any[] => this.result = result); }