首页 文章

如何过滤Observable onKeyUp?

提问于
浏览
1

如何搜索/过滤类型字符串数组的可观察对象?

例如,我有以下观察

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'));
    }
}

2 回答

  • 1

    你在这里犯了一些错误 .

    • 为什么要将observable映射到 names.indexOf(value) > 0.map() 从字面上转换了observable,你刚刚输入了一个 string 类型的observable来输入 boolean .

    • 如果您希望在用户键入时更改 names 列表(onkeyup),为什么还要将 this.names$ 重新分配回 this.names$ ?这将使您的代码只能在第一次击键时工作 . 你应该有两个变量,一个用于保存值,另一个用于绑定到 ngModel .

    • 如果要使用 async 管道,则无需在打字稿文件中订阅observable .

    ngOnInit() 中,创建一个变量来跟踪您的姓名:

    ngOnInit() {
        this.data$ = Observable.of(['Lenovo', 'Dell', 'Toshiba', 'Apple', 'Microsoft']);
        this.names$ = this.data$;
    }
    

    假设您正在使用 async 管道,这应该是您的 onKeyUp 函数:

    onKeyUp(value) {
        this.names$ = this.data$
            .map(x => {
                 return x.filter(y=>y.toLowerCase().indexOf(value.toLowerCase())>-1);
            })
    }
    

    工作Stackblits:https://stackblitz.com/edit/angular-yeaer6

  • 1

    试试这个

    let value='Del'
     Rx.Observable.from(['Lenovo','Dell','Toshiba','Apple','Microsoft'])
     .filter(name=>name.indexOf(value)!==-1)
     .subscribe(console.log);
    

相关问题