Filtering JSON data in Ionic 4 based on multiple values

Recently, I've encountered an issue with filtering a local JSON file based on multiple criteria. Initially, I thought that combining conditions using '&&' would solve the problem. However, when the data is loaded into Ngx-Datatable, nothing shows up. Filtering works fine with a single condition, so it's puzzling why multiple criteria don't work. Could the problem be in the JSON file? Do I need to use a different approach? Or is it related to how I'm loading the data view? I'm intrigued as to why this isn't working because I assumed that .filter() could handle multiple criteria since it worked with a single condition before.

TypeScript File

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import data from './../../assets/pathrequests.json';
import { NavController } from '@ionic/angular';
import { NavigationExtras } from '@angular/router';
import { AlertController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


@Component({
  selector: 'app-view-necropsy-details',
  templateUrl: './view-necropsy-details.page.html',
  styleUrls: ['./view-necropsy-details.page.scss'],
})
export class ViewNecropsyDetailsPage implements OnInit {

  pathrequestid: string;
  procedureid: string;
  requestdate: string;
  animalqty: string;
  marker: string;
  method: string;
  fixative: string;
  handling: string;
  processing: string;

  items: any[];
  private pathrequests: any[] = data;
  tablestyle = 'bootstrap';


  constructor(private alertCtrl: AlertController, private http: HttpClient, private route: ActivatedRoute, private router: Router, public navCtrl: NavController) { }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.pathrequestid = params["pathrequestid"];
      this.procedureid = params["procedureid"];
      this.requestdate = params["requestdate"];
      this.animalqty = params["animalqty"];
      this.marker = params["marker"];
      this.method = params["method"];
      this.fixative = params["fixative"];
      this.handling = params["handling"];
      this.processing = params["processing"];
    });
    this.loadData();
  }

  loadData(){
    let data:Observable<any>;
    data = this.http.get('assets/tissue.json');
    data.subscribe(data => {
      this.items = data.filter(item => item.pathrequestid === this.pathrequestid && item.procedureid === this.procedureid);
      console.log(this.items);
    })
  }

}

HTML Template

<ion-header>
  <ion-toolbar color="primary">

    <ion-buttons slot="start"gt;
      <ion-menu-button menu ="main-menu"></ion-menu-button>
    </ion-buttons>

    <ion-buttons>
      <ion-back-button defaultHref="/view-procedure"></ion-back-button>
    </ion-buttons>

     <ion-buttons class="button_style"  slot="end">
      <ion-button (click)="switchStyle()">
        {{ tablestyle }}
      </ion-button>
    </ion-buttons>

  </ion-toolbar>
</ion-header>


<ion-content>
  
  <ngx-datatable  class="necropsydetails_table"
    [ngClass]="tablestyle" 
    [rows]="items"
    [columnMode]="'force'" 
    [headerHeight]="60" 
    [rowHeight]="'auto'">
 
    <ngx-datatable-column name="tissue"></ngx-datatable-column>
    <ngx-datatable-column name="collectflg"></ngx-datatable-column>
    <ngx-datatable-column name="weighflg"></ngx-datatable-column>
    <ngx-datatable-column name="photoflg"></ngx-datatable-column>
    <ngx-datatable-column name="tissuecomment"></ngx-datatable-column>

  </ngx-datatable>


</ion-content>

Answer №1

After thorough testing, we can eliminate the filter as a potential issue. It would be helpful for others if you could also share the template.

Based on the information provided, the problem may lie with the model or template, sometimes requiring manual intervention to force rendering (e.g. Change detection in Angular). Some suggestions include:

  1. Hold off on displaying the results view until items are assigned properly.

  2. Try moving the filter inside a pipe and utilizing the async pipe to show the already-filtered data. Keep in mind that items should be an Observable.

     this.http.get('assets/tissue.json')
     .pipe(filter(item => /*criteria here*/)
    

Then, in the template section:

    *ngFor="let item of items | async"

I hope these suggestions prove useful.

Answer №2

Your filter seems to be working fine, but there could be a potential race condition or incorrect parameters causing the issue. The variable this.procedureid is being set in the queryParams asynchronous call, while loadData function is called synchronously and also triggers an asynchronous http get request.

To ensure that the data is properly loaded, you can move the call to this.loadData() inside the subscribe block as shown below:

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      // setting various params values here
      this.loadData(); // calling it inside subscribe block ensures proper data retrieval
    });
    // avoid calling it outside the subscribe block to prevent execution before params are set
    // this.loadData();
  }

While RxJS operators can offer more advanced solutions, for this simple scenario, sticking to the above approach should suffice without overcomplicating things.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for pdfjs-dist to be used with Typescript?

Is there a way to preview a PDF as a canvas without importing pdfjs-dist into my project? I have already used the command $yarn add pdfjs-dist to install pdfjs-dist. Do I need to include any additional imports? import pdfjsLib from "pdfjs-dist/build ...

What could be causing the select2 to not display the most up-to-date information in the control?

I have implemented a progressive search feature but it seems that the data returned is not populating the control properly. $("#selUser").select2({ ajax: { url: "/M01EngineeringData/GetFunctionalLocations", ty ...

Transforming Enumerated Types in Protobuf3 into JSON using the Go Programming Language

Is there a way to change a grpc/protobuf3 message into JSON with the enum represented as a string instead? Take, for instance, this protobuf message: enum Level { WARNING = 0; FATAL = 1; SEVERE = 2; ... } message Http { string messag ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

Experiencing difficulty in parsing the JSON document

I am struggling with reading a .JSON file (todo.json) in my Angular.Js project. The file is stored on the server, and all static files are saved within the 'public' folder of my basic Express server. Even though I can access the todo.json file di ...

The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'sub ...

SailingSmooth and JSONP Integration

I am currently working on a project that aims to establish a connection with Hudson CI server and other Hudson-compatible CI servers. While I initially thought that CruiseControl offers a JSONP API similar to Hudson's, I have been unable to find any d ...

Securing your Angular2 application with TypeScript for enhanced safety

Looking to create a web application using Angular2 with TypeScript. After researching authentication in Angular2, it seems I need to include the following components: index component (public) login component (public) my private component (private) Thes ...

Retrieve all the data from a MySQL table without applying any filters

My query is not returning the expected results and instead fetching all rows from the table. I am specifically trying to filter rows where the job_category field equals "Marketing" but can't seem to figure out the issue. Below is my query statement a ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

The JSON representation is not appearing for the newly introduced nested components

Building a nested component within another component and implementing two-way binding for dynamically added field values using the JSON pipe in the view. However, encountering an issue where the newly added values are not reflected in the JSON view. If yo ...

Combining two disciplines within a single database column

Take a look at my DEMO and help me with this question: Why is the date in the values of HTML offset 2 not showing as a date, but rather as a number? DEMO: $data = array(); $data_1 = $_POST['data_1']; $static = $_POST["static"]; foreach($static ...

In order to access and showcase the current positions of each ngfor element, you need to obtain a reference to them

I am looking to retrieve references for each of the ngFor elements and display their latest Top and Left positions. Since these elements are draggable, their positions will be changing. While I can obtain a value for a single element, I am facing an issue ...

Updating the appearance of a non-declared HTML child component on-the-fly using Angular

Trying to dynamically adjust the style of an unspecified div is causing some trouble. Using Angular and PrimeNG, invisible divs are being generated that I cannot access through inline styles. The objective is to allow a user to input a width as a string (5 ...

When implementing asynchronous form control validation in Angular 2, several API requests are triggered

Can anyone help me with adding async validation using a FormControl? For every keypress, I am receiving multiple responses and it seems like an extra request is triggered whenever I type or remove a character in the form control. code-snippets.component.t ...

Executing a Function in a Service from a Component in Angular/TypeScript and Receiving a Return Value

I need guidance on how to effectively utilize the "getUserDocInfo()" function from a separate service within my component. How can I call this function and then leverage the data it returns for further operations? Component Example getToken(){ this. ...

Adjusting the height of an Angular CDK virtual scroll viewport based on dynamic needs

Currently, I am developing an Angular table with the cdk Virtual Scroll feature. Is there a method to adjust the scroll viewport's height dynamically? While the standard style property works, I am encountering difficulties setting the value using ngSt ...

Looking for a regular expression to verify if the URL inputted is valid in TypeScript

After conducting thorough research, I discovered that none of the suggested URLs met my criteria, prompting me to raise a new query. Here are my specific requirements: * The URL may or may not include 'http' or 'https' * The URL can co ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Steps for creating a jasmine test suite

I'm currently creating a unit test for Angular2 using Jasmine. Below is the code snippet I am working with: component.ts toggleSelect() { this.checked = event.target.checked this.tree.forEach(t => { t.checked = this.checked }) ...