简体   繁体   中英

Filter HTTP JSON response by nested value in Angular 6

I want to fetch some JSON data from an external source and display it in a <select> - & <option> -Tag in my view. So far so good.

Some JSON entries have a private: false value. And this is where my question comes in. My destination is it, to only show the user the entries containing the private value set to false.

I already looked for JSON filter and found out that I could set a filter in my view in ngFor ( let appointmentType of appointmentTypes | filter: { private: false } ), but I get an error message telling me that The pipe 'filter' could not be found .

This is the URL I had my solution from: ng-repeat :filter by single field

This is the JSON response:

[
  {
    "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
  }
]

This is my HTML

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

This is my Component.TS File:

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);
    });
  }
}

And don't know if it's necessary, but here's my api.service.ts:

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

As I said, I managed it do display the JSON Response entries in the select option, but I only want to provide the ones where private is set to false.

The filter in angularjs is different from pipe in angular . you need to implement own custom pipe to make your logic work.

your pipe should be like this,

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

You are going to have to create your own custom pipe to do the filtering of the users list.

Angular doesn't provide pipes for filtering or sorting lists. Developers familiar with AngularJS know these as filter and orderBy. There are no equivalents in Angular.

https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

This decision was made because of he inheret performance implications of allowing these types of native pipes.

I have put together a stackblitz with the solution here: https://stackblitz.com/edit/angular-pqeky2

As you can see the third user who has privacy: false does not appear in the select list because it is filtered out by the custom pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM