【问题标题】:Observable filter angularjs 2可观察过滤器angularjs 2
【发布时间】:2016-02-16 22:35:50
【问题描述】:

我想根据用户输入的文本过滤我的表格列。我正在使用以下管道,

import {Pipe, PipeTransform} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/filter';

@Pipe({
    name: "search"
})
export class SearchPipe implements PipeTransform {
    searchTerms: Map<string, string> = new Map<string, string>();
    key: string;
    term: string = "*";

    transform(input, [colIndex, term, key]) {
        console.log("start of search " + term + " key:" + key);
        this.key = key;
        this.term = term;

        if (this.term == '*') {
            return input;
        } else {

             input.filter(
                function(data) {
                    data.forEach(
                        e=> {
                            console.log("filtering data " + e[key]+" result is : "+e[key].contains(term));
                            return e[key].contains(term);
                        }
                    )
                }
            ).subscribe(
                function(err) {
                    console.log('Error: %s', err);
                },
                function() {
                    console.log('Completed');
                }
              )


        }
    }

}

在我的html页面中,

<tr *ngFor="#column of (tableData.columns | search:columnIndex:filterTerm:columnKey | async )" (click)="onRowSelect(column)">
            <td *ngFor="#key of column | jsonIterator">{{column[key]}}</td>
        </tr>

tableData.columns 是 Observable 类型,我从一个内容为的 json 文件中获取,

[{"Component ID":"1","Component Type":"abc","Label Value":"user ID","Tool Tip Value":"please enter user ID"},
{"Component ID":"2","Component Type":"oit","Label Value":"user name","Tool Tip Value":"please enter user name"}
]

'term' 是输入的文本,将根据 json 中的 'key' 的值进行搜索。 JsonIterator 是我在 json 中获取密钥的另一个管道

当用户输入文本时,我的数据表会被清理。 我错过了什么?

而且我的方法是否正确?由于我是 angular js 2 的新手,因此我不知道实现此类组件时遵循的约定。 我的意思是这是用户过滤可观察对象的正确方法还是我应该使用地图或其他东西?

列数据填充为,

this.tableBean.columns = this.http.get('appLiteral.json')
    .map(res => res.json());

【问题讨论】:

  • tableData.columns 是异步的(可观察的)吗?请提供有关数据来源的更多信息。
  • 如果 term != '*' ,您不会返回过滤后的列

标签: typescript angular observable


【解决方案1】:

我会恢复您在 ngFor 中应用过滤器的顺序。我会将异步管道放在 observable 之后:

<tr *ngFor="#column of (tableData.columns | async |search:columnIndex:filterTerm:columnKey)" (click)="onRowSelect(column)">

并从您的自定义管道中删除 observable api 的使用。

事实上,当从 observable 接收到数据时,管道会再次调用这些数据。您将能够在自定义管道中过滤它们。

您的代码的问题是您在自定义管道中的 subscribe 方法中没有定义任何内容。所以你的管道什么都不返回(没有数据)......

如果您真的想在自定义管道中利用 observable,可以查看此链接:

https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/async_pipe.ts

【讨论】:

    猜你喜欢
    • 2016-11-19
    • 2018-07-10
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多