首页 > 解决方案 > 在Angular 6中按嵌套值过滤HTTP JSON响应

问题描述

我想从外部源获取一些 JSON 数据并将其显示在我视图中的<select>- & <option>-Tag 中。到现在为止还挺好。

一些 JSON 条目具有private: false值。这就是我的问题所在。我的目的地是它,只向用户显示包含private设置为 false 的值的条目。

我已经查找了 JSON 过滤器,并发现我可以在 ngFor( let appointmentType of appointmentTypes | filter: { private: false }) 中的视图中设置过滤器,但我收到一条错误消息告诉我The pipe 'filter' could not be found

这是我的解决方案的 URL: ng-repeat :filter by single field

这是 JSON 响应:

[
  {
    "id": 5780379,
    "name": "Appointment Type 1",
    "description": "",
    "duration": 15,
    "price": "290.00",
    "category": "REGULAR",
    "color": "#3177CA",
    "private": false
  },
  {
    "id": 5780481,
    "name": "Appointment Type 2",
    "description": "",
    "duration": 15,
    "price": "39.00",
    "category": "SERVICE",
    "color": "#D8394F",
    "private": true
  }
]

这是我的 HTML

<select type="appointmentType" [(ngModel)]="appointmentTypeId">
  <option *ngFor="let appointmentType of appointmentTypes | filter: { private: false }" [ngValue]="appointmentType.id">{{appointmentType.name}}</option>
</select>
{{appointmentTypeId}}

这是我的 Component.TS 文件:

import { Appointment } from './../../appointments/appointment';
import { Component, OnInit } from '@angular/core';
import { APIService } from './../../../api.service';

@Component({
  selector: 'app-booking',
  templateUrl: './booking.component.html',
  styleUrls: ['./booking.component.scss']
})
export class BookingComponent implements OnInit {
  private appointmentTypes: Array<object> = [];
  appointmentTypeId: any;

  constructor(private apiService: APIService) {}

  ngOnInit() {
    this.getData();
    console.log(this.appointmentTypeId);
  }

  public getData() {
    this.apiService.getAppointmentTypes().subscribe((data: Array<object>) => {
      this.appointmentTypes = data;
      console.log(data);
    });
  }
}

不知道是否有必要,但这是我的 api.service.ts:

getAppointmentTypes() {
  return this.httpClient.get(`${this.API_URL}/appointment-types/`);
}

正如我所说,我管理它确实在选择选项中显示 JSON 响应条目,但我只想提供private设置为 false 的条目。

标签: javascriptjsonangularhttpfilter

解决方案


angularjs 中的过滤器与 angular 中的管道不同。您需要实现自己的自定义管道以使您的逻辑正常工作。

你的烟斗应该是这样的

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'filter' })
export class filterPipe implements PipeTransform {
  transform(categories: any, searchText: any): any {
     let result = categories.filter(t=>t.private == searchText);
     return result;
  }
}

STACKBLITZ DEMO


推荐阅读