Angular search results coming back as null

I am currently building a search feature for my app (using Angular 14 + Ionic 6) that searches via API call using the GET method. Struggling with an issue where it keeps returning 'undefined' in the console, and also encountering a problem with a pipe. Whenever I input text into the search bar, I receive this error in the console:

TypeError: Cannot read properties of undefined (reading 'filter')

Would appreciate any assistance or guidance on how to resolve these issues. Thank you! :)

search.service.ts:

  searchCall(term: string) {
    return from(Preferences.get({key: 'TOKEN_KEY'})).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        let params = new HttpParams();
        params = params.append('term', term);
        return this.httpClient.get(`${environment.apiUrl}search`, {headers, observe: 'response', params});
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log(err.error.message);
        }
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigateByUrl('/login', {replaceUrl: true});
        }
        return EMPTY;
      }),
    );
  }

search.page.ts:

export class SearchPage implements OnInit {
  term = '';
  products: any = {
    id: '',
    name: '',
    product_code: '',
  };

  constructor(
    private searchService: SearchService,
  ) { }

  ngOnInit() {
    this.search(this.term);
  }

  search(term: string) {
    this.searchService.searchCall(term).subscribe(
      (data: any) => {
        console.log('Search: ' + data.body.products);
      },
      error => {
        console.log('Error', error);
      }
    );
  }

}

search.page.html:

<ion-content [fullscreen]="true" class="ion-padding">
  <ion-searchbar [debounce]="1000" placeholder="Search" show-clear-button="focus" [(ngModel)]="term"></ion-searchbar>
  <ion-list>
    <ion-item *ngFor="let produkt of products?.results | filter : term">
      <ion-label>{{ produkt.product_code }} {{ produkt.name }}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>

filter.pipe.ts:

export class FilterPipe implements PipeTransform {

  public transform(value: any[], filterText: string) {
    return filterText.length > 3 ? value.filter(x => x.name.toLowerCase().includes(filterText.toLowerCase())) : value;
  }

}

EDIT: Adding code snippet from import modules as per comments request: My filter pipe is included within the shared.module.ts file:

import { NgModule } from '@angular/core';
import { CommonModule } from '@common';
import { FooterComponent } from '../navigation/footer/footer.component';
import { RouterLink } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { SideMenuComponent } from '../navigation/side-menu/side-menu.component';
import { SafeHtmlPipe } from '../pipes/safe-html.pipe';
import { FilterPipe } from '../pipes/filter.pipe';



@NgModule({
  declarations: [FooterComponent, SideMenuComponent, SafeHtmlPipe, FilterPipe],
  imports: [
    CommonModule,
    RouterLink,
    IonicModule
  ],
  exports: [FooterComponent, SideMenuComponent, SafeHtmlPipe, FilterPipe]
})
export class SharedModule { }

API JSON response format:

[
    {
        "id": 3,
        "name": "test",
        "product_code": "45623146546"
    },
]

Answer №1

The issue you are facing is most likely related to how the filter function is being called. Based on your updated question, it seems that the pipe itself is imported correctly.

To troubleshoot this issue, consider adding a console.log statement to your pipe code like this:

export class MyFilterPipe implements PipeTransform {

  public transform(data: any[], searchText: string) {
    console.log('data:', data, 'searchText:', searchText);
    return searchText.length > 3 ? data.filter(item => item.name.toLowerCase().includes(searchText.toLowerCase())) : data;
  }

}

By checking the console output, you may discover that the expected input for data is not an array as anticipated.

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

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...

Is there a way to show an incorrect username and password message directly above the sign-in form?

Is there a way to have an error message display just above the sign-in form if the username and password are incorrect? I don't want it to redirect to another page, but simply show the error right above the form in my code. <!Doctype html> < ...

Having trouble retrieving JSON data using http.get method, as the status returned is -1

I'm a beginner in AngularJS. I'm attempting to retrieve JSON data in my code using $http.get, but it's throwing an error and the status is showing as -1. What could be causing this issue? RecordApp.factory('recordaccess', [' ...

Complete circular gauge in Ionic

Encountering an issue when attempting to incorporate a complete circle Gauge/Gage in Ionic, as the gauge fails to display. Has anyone managed to successfully include a full circle Gauge in Ionic similar to this: https://i.sstatic.net/OKcpD.jpg Came acro ...

Typescript: The type 'X' does not correspond with the signature '(prevState: undefined): undefined' in any way

My React Native app, which is written in TypeScript, has been giving me a hard time with an error lately. The issue revolves around a Searchable List feature. This list starts off with an Array of values and gets updated when users type into a search bar. ...

Expanding an array in JavaScript

I need assistance with... let a = ['a', 2, 3]; a += function(){return 'abc'}; console.log(a[3]); Therefore, I am looking for a shorthand method to push() in array with the above content. Does anyone know of an operator that can help ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

The number associated with the 'pipe' is currently unavailable

After successfully migrating my application from Angular 4 to 7, I encountered an issue during compilation (ng build --prod). The error message displayed was: ERROR in : Template parse errors: The pipe 'number' could not be found (" </d ...

Vue hover effect not triggering updates to the state

I have been attempting to attach a v-mouseover directive to a bootstrap Vue component called b-list-group-item in the following code snippet. <b-row> <b-col cols="3"> <b-list-group> <b-list-group-ite ...

Guide on changing image source using a function

I am looking to dynamically set the img src="" attribute using a JavaScript function that changes the image based on a variable and checks its values: Here is the JavaScript code in the file: function myFunctionstatus(){ var ledactual = document.getE ...

Exporting multiple sheets using Angular's ngx-export-as functionality

Currently utilizing ngx-export-as in my Angular project and I am looking to export an Excel file with multiple sheets. How can I achieve this export functionality? I have raised a concern regarding this on GitHub. ...

Adjust the mesh position in THREE.js following the implementation of the EdgesHelper

Despite my attempt to rotate or reposition a mesh following the application of EdgesHelper, the desired effect is not achieved — the mesh remains in its original position. (Interestingly, it works perfectly fine without the EdgesHelper). What could be ...

Discover the most concise string within the array

Is there a way to determine the shortest string in a JavaScript array regardless of the number of elements it contains? I attempted using var min = Math.min(arr[0].length,arr[1].length,arr[2].length); to find the shortest string among 3 elements in an ar ...

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Tips for using NodeJS with a MySQL database

Hello everyone, I'm new to this community so please bear with me if my question seems too simplistic. I've been tasked with a basic web project for one of my courses and will be using NodeJS+MySQL along with VS Code which has caught my eye. Howe ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...

How to change a date object into a datestring using the TZ format in JavaScript

Here is the input: const date = "06/01/2018" const time = "06:25:00" The desired output format is a string like this: "2018-06-01T00:55:00.000Z". I attempted to create the Date object using const result = new Date(date + time); //outputs an obje ...

Making @types compatible with TypeScript 2.1 in Visual Studio 2015 Update 3

The potential of TS 2.x @types is intriguing, but I'm struggling to make it work effectively! I'm using Visual Studio 2015 - version 14.0.25431.01 Update 3 My TypeScript version for Visual Studio 2015 is 2.1.4, downloaded from this link The VS ...