javascript - 在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 的条目。
解决方案
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;
}
}
推荐阅读
- python - 如何使用官方 Python 客户端从 Pod 中查找同一节点上的所有 Kubernetes Pod?
- jquery - 以多阶段形式使用 Jquery 禁用选项卡的问题
- spring - Spring Boot 2.0.5 中来自 PrometheusPushGateway 的 @PreDestroy 注释的 BeanCreationNotAllowedException
- git - Git检测逻辑重复文件并失败合并
- php - 动态数组 php(在 relod php 表单后将数据附加到数组)
- python-3.x - 运行 jupyter notebook 时没有名为 nbbrowserpdf.exporters.pdf 的模块
- google-bigquery - 将表名(动态)引用为 bigQuery 中的列
- arrays - 嵌套数组根据 2 个条件返回总和和每个金额
- sql - SQL Server:Concat 中途停止
- r - 根据匹配删除某些行