[英]Filter HTTP JSON response by nested value in Angular 6
我想從外部來源獲取一些JSON數據,並在視圖中的<select>
-& <option>
-Tag中顯示它們。 到現在為止還挺好。
一些JSON條目具有一個private: false
值。 這就是我的問題所在。我的目的地是它,僅向用戶顯示包含設為false的private
值的條目。
我已經在尋找JSON過濾器,發現可以在ngFor的視圖中設置過濾器( let appointmentType of appointmentTypes | filter: { private: false }
),但是我收到一條錯誤消息,告訴我The pipe 'filter' could not be found
。
這是我從以下解決方案獲得的網址: ng-repeat:按單個字段過濾
這是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/`);
}
就像我說的那樣,我管理它確實在select選項中顯示JSON Response條目,但是我只想提供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;
}
}
您將必須創建自己的自定義管道來過濾用戶列表。
Angular不提供用於過濾或排序列表的管道。 熟悉AngularJS的開發人員將其稱為filter和orderBy。 Angular中沒有等效項。
https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
之所以做出此決定,是因為他允許使用這些類型的本機管道會對性能產生影響。
我在這里將解決方案放到了stackblitz上: https ://stackblitz.com/edit/angular-pqeky2
如您所見,第三個具有隱私權的用戶:false不會出現在選擇列表中,因為它已被自定義管道過濾掉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.