Angular2—搜索功能(管道)

Angular2入坑指南——管道(搜索功能)
想必大家做项目都会遇到搜索功能吧,通常都是搜索本地数据,如果通过http去请求后台再回显的话,那响应速度简直叫人抓狂,所以大多数都是先存到本地然后进行搜索回显。Angular1的方法很简单,只需要在input标签加入ng-model,然后再在想要显示数据的标签加上| filter就好了,然而,Angular2移除了filter和orderBy,他们的理由是:感觉filter和orderBy响应很慢。我想问:什么是快?怎么快?达到多少KB/s算快?这就要求我们自己写方法来实现了,但是文档提供的仅仅只有那么几个管道,根本没有我们想用的,于是我就自己写了一个搜索关键字的小demo,在这里和大家分享下,不足之处还请多提意见给我哦。

首先创建一个名为*.pipe.ts的文件,然后在其中引入Pipe、PipeTransform和Injectable:

import { Pipe, PipeTransform, Injectable } from '@angular/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 items.filter(searchCtrl);
    }
};
  

然后在module中注册它,使它生效:

declarations: [ SearchFilter ],
exports: [ SearchFilter ]

生效后就可以在module下的所有模块中使用了,直接填写管道名称就可以啦,比如下面的例子:

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

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

之后,只要在搜索框里输入内容时就会动态显示搜索内容啦
参考http://www.cnblogs.com/Speykey521/p/7136953.html

输入某一条件,点击搜索,请求如下: find_by_spec?sort=updateDate,desc&gameType=2 在此基础上,点击下一页,请求如下: find_by_spec?sort=updateDate,DESC&page=1 问题:限制条件gameType=2 丢失了 ,所以点击第二页之后,所显示的数据,是在没有任何限制条件下的数据,怎样才能实现 条件查询之后,点击下一页之后,所显示的仍是条件之下的数据呢(假设表单数据较多,一页20条,放不下!需要点击下一页) 分页组件:///////////////////////////////////////////////////////////////// import {Component, Input, OnInit} from '@angular/core'; import {Router} from '@angular/router'; @Component({ selector: 'app-page-helper', template: ` <div class="row justify-content-center" *ngIf="pageModel?.page?.totalPages > 1"> <div class="col-8"> <div style=" width: auto;display: table;margin-left: auto;margin-right: auto;"> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-end"> <li class="page-item" [class.disabled]="!pageModel?._links?.share"> <span class="page-link">   共:{{pageModel?.page?.totalElements}} 条,每页{{pageModel?.page?.size}} 条</span> </li> <li class="page-item" [class.disabled]="!pageModel?._links?.first"> <a class="page-link" href="javascript:void(0);" (click)="page=0;nextPage()">首页</a> </li> <li class="page-item" [class.disabled]="!pageModel?._links?.prev"> <a class="page-link" href="javascript:void(0);" (click)="page=page-1;nextPage()" tabindex="-1">上一页</a> </li> <li class="page-item" *ngFor="let item of pageItemLength()" [class.active]="pageModel?.page?.number==item"> <a class="page-link" href="javascript:void(0);" (click)="page=item;nextPage()">{{item + 1}}</a> </li> <li class="page-item" [class.disabled]="!pageModel?._links?.next"> <a class="page-link"href="javascript:void(0);" (click)="page=page+1;nextPage()" >下一页</a> </li> <li class="page-item" [class.disabled]="!pageModel?._links?.last"> <a class="page-link" href="javascript:void(0);" (click)="page=pageModel.page.totalPages-1;nextPage()">最后一页</a> </li> </ul> </nav> </div> </div> </div>` }) export class PageHelperComponent implements OnInit { // 当前页 page = 0; url = ''; @Input() pageModel: any; constructor(private router: Router) { } ngOnInit(): void { this.url = this.router.url; } nextPage() { { this.router.navigate([this.url, {page: this.page}]);} } pageItemLength(): number[] { if (!this.pageModel) { return []; } const page = this.pageModel.page.number; const pages = this.pageModel.page.totalPages; const values: number[] = []; if (pages > 10) { for (let i = 6; i > 0; i--) { if (page - i >= 0) { values.push(page - i); } } for (let x = 0; x < 6; x++) { if (page + x < pages) { values.push(page + x); } } } else { for (let y = 0; y < pages; y++) { values.push(y); } } return values; } } 市场折扣的组件://///////////////////////////////////////////////// import {Component, OnInit} from '@angular/core'; import {MarketService} from '../market.service'; import {ActivatedRoute} from '@angular/router'; import {SearchModel} from '../../shared/search.model'; @Component({ templateUrl: './market-rebate-list.component.html' }) export class MarketRebateListComponent implements OnInit { searchModel = new SearchModel(); pageModel: any; platformModel: any; proposerModel: any; constructor(private server: MarketService, private route: ActivatedRoute) { } ngOnInit(): void { this.route.data.forEach((data: { model: any }) => this.pageModel = data.model); /* //获取所有平台*/ this.server.getModels('/api/market_rebate/search/platforms').subscribe(res => this.platformModel = res); /* //获取所有提交人*/ this.server.getModels('/api/market_rebate/search/verifier').subscribe(res => this.proposerModel = res); } searchData() { this.server.getModels('/api/market_rebate/search/find_by_spec?sort=updateDate,desc' + this.searchModel.toQueryParams()).subscribe(res => this.pageModel = res); } deleteRebate(model: any) { if (confirm('你确定要删除折扣ID为:' + model.id + '的折扣吗?')) { this.server.postModel('/api/market_rebate/delete', model).subscribe((res: any) => this.refreshData()); } } refreshData() { this.server.getModels(this.pageModel._links.self.href) .subscribe(data => this.pageModel = data); } } 市场组件预加载:///////////////////////////////////////////////// import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, Resolve} from '@angular/router'; import {MarketService} from '../market.service'; import {Observable} from 'rxjs/Observable'; @Injectable() export class MarketRebateResolve implements Resolve<any> { constructor(private server: MarketService) { } resolve(route: ActivatedRouteSnapshot): Observable<any> | boolean { const params = route.params['id']; if (params) { if (params !== 'add') { const id = +route.params['id']; return this.server.getModels('/api/market_rebates/' + id).map(data => { if (data) { return data; } return true; }); } } else { const page = route.params['page'] ? +route.params['page'] : 0; return this.server.getModels('/api/market_rebate/search/find_by_spec?sort=updateDate,DESC&page=' + page).map(data => { if (data) { return data; } else { return false; } }); } } } 拜托各位了
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页