无法对json文件中存在的数据应用搜索过滤器

时间:2018-08-03 12:02:45

标签: json angular angular6 angular-pipe

这是我的(custom.component.html)文件

    <input ng-model="searchText" placeholder="&nbsp;&nbsp;Enter the name" 
            class="seacrh-field"><br><br>

     <mat-card class="example-card" *ngFor="let spaceScreen of 
               spaceScreens; 
                   let i = index">

        <mat-card-header>
           <div mat-card-avatar class="example-header-image" >
                <img mat-card-image class="list-img" src=" 
              {{spaceScreen?.img}}" >
          </div>

          <mat-card-content class="names">{{ spaceScreen?.name }} 
          </mat-card-content>
       </mat-card-header>

    </mat-card>

这是(custom.component.ts)文件

            import { Component, OnInit } from '@angular/core';
            import { Http } from '@angular/http'; 
            import { map } from 'rxjs/operators'

            @Component({
              selector: 'ylb-customer',
              templateUrl: './customer.component.html',
              styleUrls: ['./customer.component.css']
            })
            export class CustomerComponent  {

              spaceScreens: Array<any>;

              constructor(private http:Http){
                this.http.get('assets/app.json').pipe(
                  map(response => response.json().screenshots)
              ).subscribe(res => this.spaceScreens = res);
                }


            }

这是资源文件夹中存在的(app.json)文件

            {   
        "screenshots":[ 

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Virat Kohli"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Joe Root"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Adam Gilchrist"
                    },
                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Kevin Peterson"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Misbhah-Ul-Hak"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"ABD Develliers"
                    },
                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Ben stokes"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Chris Gayle"
                    }

            ]        
        }

一切正常,我如何将搜索过滤器(例如移动设备中的联系人列表)应用于app.json文件中存在的数据。尝试了许多方法,但仍然没有结果。如何使用自定义管道轻松实现

1 个答案:

答案 0 :(得分:0)

在Angular 1中,大多数人使用管道进行过滤。 trichetriche 在其他答案的评论中指出了这一点,这是正确的。问题在于,这种行为会导致性能下降,因为每个摘要周期都会触发过滤(并且这种情况经常发生)。因此,在Angular 2+中,他们希望您将结果过滤到组件中并将结果存储在数组中,然后只需使用* ngFor =“ myFilteredArray”。

首先设置对您输入内容的绑定,以便我们获得用户想要搜索的内容。

//Use this method if you want to track name for more than a filter.  
//Result will be stored in name var
<input type="text" [(ngModel)]="name" (ngModelChange)="onNameChange()">
//Use this if you don't need to track the name text for anything else.
<input type="text" (input)="onNameChangeInput($event.target.value)">

<div *ngFor="let s of filteredScreenshots">
  {{s | json}}
</div>

第二向组件添加更改功能。ts

您将要使用lodash或下划线之类的库。 如果您没有lodash,请使用-https://lodash.com/docs

npm install lodash

component.ts

import * as _ from 'lodash';

export class CustomerComponent  {

    spaceScreens: Array<any>;
    filteredScreens = [];
    name: string;

    constructor(private http:Http){
        this.http.get('assets/app.json').pipe(
              map(response => response.json().screenshots)
          )
          .subscribe(res => {
              this.spaceScreens = res; //this is what we filter against
              this.filteredScreens = res; //init with full list
         });
    }

    onNameChange() {
        this.filteredScreens = _.filter(this.spaceScreens, (screenshot) => {
             const name = screenshot['name'];
             const filteredName = this.name.toUpperCase();
             return name === undefined ? false : name.toUpperCase().startsWith(filteredName);
        });
    }

    onNameChangeInput(filteredName: string) {
        this.filteredScreens = _.filter(this.spaceScreens, (screenshot) => {
            const name = screenshot['name'];
            filteredName = filteredName.toUpperCase();
            return name === undefined ? false : name.toUpperCase().startsWith(filteredName);
       });
    }
}

您只需要使用一个输入和一个更改函数,它们的命名就适当了,因此很明显每个输入都使用哪种方法。

编辑: 我忘了提到此解决方案不区分大小写,因为通常在这样的搜索中,您并不关心大小写。如果要区分大小写,请删除.toUpperCase()。