Error message: TypeScript throwing an error stating that the method is undefined while trying to implement

My goal is to create a filter interface in Angular2 using pipes. Here's how I have implemented it:

export interface IFilterable{
passesFilter(f : string, isFilter: boolean): boolean;
}

The implementation of the interface is seen in the following Server class:

import {IFilterable} from './i-filterable';
import {Contains} from '../helpers/pipe-helpers';

export class Server extends Dto implements IFilterable {
name: string;
hostname: string;
ips: string;
operatingSystem: string;
sitesCount: number;
databasesCount: number;

passesFilter(f: string, isFilter: boolean): boolean {
    console.log('in server');
    if (!f || f === '') return isFilter;
    f = f.toLowerCase();

    return Contains(this.name, f) ||
        Contains(this.hostname, f) ||
        Contains(this.ips, f) ||
        Contains(this.operatingSystem, f);
}
}

The pipe used for filtering looks like this:

import { Pipe, PipeTransform } from '@angular/core';
import {Contains} from '../helpers/pipe-helpers';
import {IFilterable} from '../models/i-filterable';

@Pipe({ name: 'serverFilter' })
export class ServerFilterPipe implements PipeTransform {
  transform(values: IFilterable[], search: string, isFilter: boolean):      IFilterable[] {
     console.log(search + ' search' + isFilter + values);
    return values.filter(value => {
    console.log(value.passesFilter);
    return value.passesFilter(search, isFilter)
  });
 }
}

However, I am facing issues as the second console.log in the pipe prints undefined and passesFilter function is not being called. Additionally, an error message "TypeError: setting a property that has only a getter" is encountered.

I then attempted to implement the same functionality using an abstract class instead of an interface:

export abstract class Dto {
abstract passesFilter(f: string, isFilter: boolean): boolean;
}

This alternative approach was applied to the Server class as well:

import {Dto} from './dto';
import {Contains} from '../helpers/pipe-helpers';

export class Server extends Dto {
name: string;
hostname: string;
ips: string;
operatingSystem: string;
sitesCount: number;
databasesCount: number;

passesFilter(f: string, isFilter: boolean): boolean {
    console.log('in server');
    if (!f || f === '') return isFilter;
    f = f.toLowerCase();

    return Contains(this.name, f) ||
        Contains(this.hostname, f) ||
        Contains(this.ips, f) ||
        Contains(this.operatingSystem, f);
}
}

Here is the updated implementation of the pipe with the abstract class:

import { Pipe, PipeTransform } from '@angular/core';
import {Dto} from '../models/dto';

@Pipe({ name: 'serverFilter' })
export class ServerFilterPipe implements PipeTransform {
transform(values: Dto[], search: string, isFilter: boolean): Dto[] {
console.log(search + ' search' + isFilter + values);
return values.filter(value => {
  console.log(value.passesFilter);
  return value.passesFilter(search, isFilter)
});
 }
}

Lastly, the helper function Contains used in the process:

export function Contains(val: string, cmp: string) {
    return val ? val.toLowerCase().indexOf(cmp) >= 0 : false;
}

Answer №1

It appears that the input of your pipe is not visible. Perhaps the values are not of type IFilterable? Regardless, it is advisable to validate the values before using them. They may be undefined during the initial pipe round.

@Pipe({ name: 'serverFilter' })
export class ServerFilterPipe implements PipeTransform {
   transform(values: IFilterable[], search: string, isFilter: boolean): IFilterable[] {
      console.log(search + ' search' + isFilter + values);
      if (!values || !values.length) return []; // ensure the input is valid!

      return values.filter(value => {
         if (!value || !value.passesFilter) return false; // validate the value 

         console.log(value.passesFilter);
         return value.passesFilter(search, isFilter)
      });
   }
}

Additionally, please note:

if (!f || f === '') return isFilter;

This validation is unnecessary as !'' evaluates to true.

UPDATE

Feel free to check out this plunker for more information: https://plnkr.co/edit/IhM4rKqD3VvEZVBdimzK?p=preview

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

"RxJS in Angular 2: The elusive map function seems to be missing

Issue: Received an error stating, "Property 'map' does not exist on type 'Observable'." import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; decl ...

Create a function that takes in an array of strings and outputs a record containing a unique key for each string in the array

Looking to create a function that takes an array of strings as input and returns an object with a key for each string in the input array? Here is an example of how this can be implemented: const getMyObject = (...keys: string[]) => keys.reduce((object, ...

Displaying a component inside a different component

I'm attempting to display components inside another component, but even when I try to include div elements within the component, they don't show up. const DisplayComponent = () => { return ( <div> <DisplayContent ...

Struggling to remove CLI from my Mac operating system

I seem to be stuck on CLI version 8.3.21 while using MacOS Big Sur. I'm not currently in a project folder and have deleted all node_modules directories from my existing Angular projects. To try and remove it, I've attempted the following commands ...

Unable to Add Stripe Client in NestJS using (https://www.npmjs.com/package/@golevelup/nestjs-stripe)

I'm currently facing an issue while trying to integrate the GoLevelUp stripe package into my NestJs project. Although I can successfully import the package into my global app module, I'm struggling to inject a functional client into the designate ...

Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I a ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...

Issue with retrieving JSON data in chart object: Error reading property 'length' of undefined in Angular/ng2-charts

     I have successfully retrieved JSON data in the following format:    [2193,3635,8417,0] The data is coming from localhost:8080. I aim to utilize this dataset for displaying a pie chart. Below is the code snippet from one.html: <div> ...

After updating NodeJS from version 8.11.1, it appears that the program is no longer functioning properly

Deciding to upgrade my nodejs version from 8.11.1 to 10.15.3, I downloaded the v10.15.3-x64.msi file on my Windows 10 system. Upon creating a fresh Angular application using the "ng new" command, I encountered the "HTTP ERROR 400" page with no errors in th ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Guide to customizing Material UI theme using Typescript in a separate file

Trying to customize Material UI theme overrides can be a bit tricky, as seen in the example below: // theme.ts const theme: Theme = createMuiTheme({ overrides: { MuiButton: { root: { display: 'inline-block', fontWeigh ...

"Seamlessly Incorporating Angular into the Hybris Platform: A Comprehensive Guide

One crucial aspect I am looking to grasp is the integration of Angular in Hybris projects for front-end development. The process involves creating Angular components and adding a proxy within the Angular application to handle mapping and calling the approp ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...

Guide to activating data transfer object validators in NEST JS

I have recently started using NEST JS and I am currently working on implementing validators in DTO's. This is what my code looks like: // /blog-backend/src/blog/dto/create-post.dto.ts import { IsEmail, IsNotEmpty, IsDefined } from 'class-validat ...

Angular is giving me a hard time setting my background image

I'm having trouble getting the background image to load on my page. No matter what I try, it just won't show up. Here's the code snippet for my page: <div class="container" [ngStyle]="{'background-image': getUrl()}"> < ...

Properly incorporating life cycle hooks into an abstract base component in Angular: A comprehensive guide

I have a unique abstract base component that includes life cycle hooks: export abstract class BaseComponent implements OnChanges, OnInit { ngOnChanges(changes: SimpleChanges): void { … } ngOnInit() { … } } Now, let's discuss a ...

How can I properly structure an if statement in React + Typescript when dealing with calling components?

I am currently attempting to showcase a component and hand over a function as a prop only when one of its state properties is true. However, I am struggling with the syntax. Here's my current setup: render = () => { return ( <ParentComponent& ...

Using a pipe to display the length of an array in Angular 4 using *ng

I'm struggling with displaying a "No Records Found" message in my app that features a range slider. Whenever the range slider is dragged, the results are updated based on the value of "sliderPipe". Despite this, I am unable to show the message when no ...

Mat-SideNav in Angular Material is not toggled by default

<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>{{applicationN ...