微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

画廊搜索管道失败

如何解决画廊搜索管道失败

嗨,我已经完成了这个过滤器管道,我想从我的所有图像中查找我的图像名称和图像 ID,但它只是从第一张图像中查找名称和 ID。 我的代码显然有任何问题。

This is my filter.pipe.ts class where I implement my search method 

import { Pipe,PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(value: any,arg: any): any {
    if (arg === '' || arg.length < 1) return value; 
    const resultPosts = [];
    for (const imagen of value) {
      if (imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1) {
        resultPosts.push(imagen);
      }else if (imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1){
        resultPosts.push(imagen);
    };
    return resultPosts;
  }
  }
}


My list.component.html where I have my input for searching:


<div class="row">
  <form class="form-inline my-2 my-lg-0">
    <input class="form-control mr-sm-2" type="text"name="filterImagen" placeholder="Search" [(ngModel)]="filterImagen"> 
    <button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
  
  </form>
    <div class="col-md-4" *ngFor="let imagen of imagenes | filter:filterImagen; index as i"> 

//when I look for the imagename or imageid,it just looks if my first image has the name I write on the searchbar

      <div class="card mb-3 animated zoomIn">
            <h3 class="card-header">{{imagen.name}}</h3>
            <div class="card-body">
              <h5 class="card-title"><b>ID: </b>{{imagen.imagenId}}</h5>
            </div>
            <div class="card-body text-center">
            <img style="height: 200px; width: 100%; display: block;" src="{{imagen.imagenUrl}}" alt="Card image">
            </div>
          </div>
    </div>
</div>

/* On my list.component.ts (here I just have a variable filter declared like: )*/

 imagenes: Imagen[] = [];
  
filterImagen = '';  //just declared it here

//我已经在 app.module.ts 和我的类中导入了我的 FormsModule。

解决方法

您是否记得将管道添加到声明中?或者更好的是,从一个模块中导出它,然后将该模块导入到 app.module 中?

更新 - 我看到你的错误:) 您必须将 return resultPosts 移出 for 循环。

如果您有兴趣,为了清晰起见,我重构了管道:

import { Pipe,PipeTransform } from "@angular/core";
import { Imagen } from "./app.component";

@Pipe({
  name: "filter"
})
export class FilterPipe implements PipeTransform {
  transform(value: Imagen[],arg: any): any {
    if (arg === "" || arg.length < 1) return value;

    return value.filter(imagen => imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1 ||
        imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1
    );
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。