【问题标题】:Unable to apply search filter for data present in json file无法对 json 文件中存在的数据应用搜索过滤器
【发布时间】:2023-03-23 03:03:01
【问题描述】:

这是我的 (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 文件中的数据。尝试了很多方法,仍然没有结果。如何使用自定义管道轻松实现

【问题讨论】:

标签: json angular angular6 angular-pipe


【解决方案1】:

在 Angular 1 中,大多数人使用管道进行过滤。 trichetriche 在另一个答案的 cmets 中指出了这一点,并且是正确的。问题是允许这种行为导致性能不佳,因为每个摘要循环都会触发过滤(这种情况经常发生)。因此,在 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>

第二在你的component.ts中添加更改函数

你会想要一个像 lodash 或 underscore 这样的库。 如果你没有 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()。

【讨论】:

  • 抱歉回复晚了。我现在收到此错误
  • 错误 TS2339:“客户组件”类型上不存在属性“屏幕截图”。
  • src/app/customer/customer.component.ts(29,38):错误 TS2339:“CustomerComponent”类型上不存在属性“名称”。 src/app/customer/customer.component.ts(35,44):错误 TS2339:“CustomerComponent”类型上不存在属性“屏幕截图”。
  • 对不起,我最后一分钟把组件变量名 screenshots 改成了 spaceScreens 并没有更新过滤器。答案已更新。问题在于 _.filter(this.screenshots) 应该是 _.filter(this.spaceScreens.
  • 你太棒了,谢谢你的所有回复。
猜你喜欢
  • 2021-02-12
  • 2020-07-27
  • 2020-05-10
  • 2017-06-24
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
相关资源
最近更新 更多