タイプstring配列で観測可能なものを検索/フィルタリングするにはどうすればよいですか?例えばObservable onKeyUpをどのようにフィルタリングできますか?
、私は今、私は、入力テキストボックスにどのようなユーザーのタイプに基づいて、この観測可能にフィルタを適用したいと思い、観察
names$ = Observable.of(['Lenovo','Dell','Toshiba','Apple','Microsoft']);
を次のようしています。
私は次のコードを持っています&入力ボックスに入力されたユーザーのsearchTermに基づいてフィルタリングされたobservableを返したいと思います。
私はクライアント側の解決策を探しています。何らかの理由でクライアント側のデータがすでに&にあります。データをフィルタするためにサーバー上に検索語を送信できません。また、この例では、配列自体にフィルターを直接使用できることを理解していますが、これを観測可能にしたいと思います。
また、フラットマップ演算子を使って配列を平坦化しようとしましたが、終わりに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間違いを指摘してくれてありがとう。それを私が直した。 – hp8888