【发布时间】:2018-05-25 17:01:53
【问题描述】:
如何搜索/过滤字符串数组类型的可观察对象?
例如,我有以下 observable
names$ = Observable.of(['Lenovo','Dell','Toshiba','Apple','Microsoft']);
现在我想根据用户在输入文本框中输入的内容来过滤这个 observable。
所以我有以下代码,我想根据用户在输入框中输入的 searchTerm 返回过滤后的 observable。
请注意,我正在寻找客户端解决方案。我的数据已经在客户端,由于某种原因,我无法在服务器上发送搜索词来过滤数据。我也明白在这个例子中我可以直接在数组本身上使用过滤器,但我想通过 observable 来做到这一点。
我也尝试过 flatmap 运算符来展平数组,但最终仍然无法返回应为字符串数组类型的 observable。
任何帮助将不胜感激。提前致谢。
App.component.html
<!-- Textbox to receive user input -->
Search:<input type='text' [(ngModel)]='searchTerm' (keypress)='onkeypress($event.target.value)'>
<p>Search Term: {{searchTerm}}</p>
<hr>
<!-- Show search results here as ordered list -->
<ng-container *ngIf='(names$|async)?.length>0'>
<ol>
<li *ngFor='let name of names$|async'>
{{name}}
</li>
</ol>
</ng-container>
App.component.ts
import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
names$: Observable<string[]>;
filteredNames$: Observable<string[]>;
searchTerm: string;
ngOnInit() {
this.names$ = Observable.of(['Lenovo', 'Dell', 'Toshiba', 'Apple', 'Microsoft']);
}
// HOW TO IMPLEMENT THIS FUNCTION ??
onkeypress(value) {
console.log(value);
this.names$ = this.names$.map(names => names.indexOf(value) > 0)
// .filter(x=>{console.log(x.indexOf(value));return x.indexOf(value)>0})
// .subscribe(
// (data)=>console.log(data), (error)=>console.log('Error'+error),
// ()=>console.log('complete'));
}
}
【问题讨论】:
-
这是一件小事,但您正在监听按键事件并调用函数 keyup。我不确定你是否有你想要的行为。
-
@Brendan Whiting 感谢您指出错误。我修好了。
标签: angular rxjs observable rxjs5 flatmap