1. 程式人生 > >Angular2入坑指南——管道(搜索功能)

Angular2入坑指南——管道(搜索功能)

意見 als brush derby 我會 不足 ng- 請求 script

想必大家做項目都會遇到搜索功能吧,通常都是搜索本地數據,如果通過http去請求後臺再回顯的話,那響應速度簡直叫人抓狂,所以大多數都是先存到本地然後進行搜索回顯。Angular1的方法很簡單,只需要在input標簽加入ng-model,然後再在想要顯示數據的標簽加上| filter就好了,然而,Angular2移除了filter和orderBy,他們的理由是:感覺filter和orderBy響應很慢。我想問:什麽是快?怎麽快?達到多少KB/s算快?這就要求我們自己寫方法來實現了,但是文檔提供的僅僅只有那麽幾個管道,根本沒有我們想用的,於是我就自己寫了一個搜索關鍵字的小demo,在這裏和大家分享下,不足之處還請多提意見給我哦。

首先創建一個名為*****.pipe.ts的文件,然後在其中引入Pipe、PipeTransform和Injectable:

import { Pipe, PipeTransform, Injectable } from [email protected]/core‘;

@Pipe({

    name: ‘searchInfos‘,

    pure: true

})

 

@Injectable()

export class SearchFilter implement PipeTransform{

    transform ( items:Array<>,args: any ): any[ ] {

        var searchCtrl = ( data: any ) => {

            var all = false;

            if ( typeof data === ‘object‘ ) {

                for ( var z in data ) {

                    if ( all = searchCtrl( data[z] ) ) {

                        break;

                    };

                };

            } else {

                if ( typeof data === ‘number‘ ) {

                    all = data === args;

                } else {

                    all = data.toString().match( new RegExp( args, ‘i‘ ) );

                };

            };

            return all;

        };

        return ietms.filter(searchCtrl);

    };

};

  

然後在module中註冊它,使它生效:

declarations: [ SearchFilter ],

exports: [ SearchFilter ]

  

生效後就可以在module下的所有模塊中使用了,直接填寫管道名稱就可以啦,比如下面的例子:

<input type="text" [(ngModel)]="search" />

<p *ngFor="let data of datas | searchInfos: search"></p>

  

之後,只要在搜索框裏輸入內容時就會動態顯示搜索內容啦~~其實也蠻簡單的。如果你覺得我的方法還有待改進之處,歡迎來稿建議哦,我會虛心接受每個人的建議喲~~還請繼續關註我哦~~

Angular2入坑指南——管道(搜索功能)