Leverage Custom_Pipe within TS

I am currently working with a pipe that I have created. Here is the code:

@Pipe({
name: 'searchNomES'
})
export class SearchNomESPipe implements PipeTransform {

transform(uos: IUo[], name?: string,): IUo[] {

if (!uos) return [];
if (!name) return uos;
name = name.toLocaleLowerCase();
uos = [...uos.filter(uo => uo.nom.toLocaleLowerCase().includes(name))];
   return uos;

}
}

When using this pipe in my HTML like so, everything works fine:

<ng-container *cdkVirtualFor="let image of display | async | searchNomES : name " >
</ng-container> 

However, when trying to use the pipe in my component.ts file, I encounter an issue. Here is what I tried:

<mat-form-field >
<input matInput  
(keyup)="applyFilter2($event.target.value)">    
</mat-form-field>

import { SearchNomESPipe } from '../../search-nomES.pipe';

constructor(private  espipe:  SearchNomESPipe) { }

ngOnInit() {this.display=this.markerservice.getGeos() }

applyFilter2(name : string) {
this.display = this.espipe.transform(this.display,name);
}

This is my service:

getGeos() { return this. 
database.list('ES').snapshotChanges().pipe(map(actions => {
return actions.map(a => {
const data = a.payload.val();
const key = a.payload.key;
return {key, ...data };

Unfortunately, running this code gives me the following error:

uos.filter is not a function or its return value is not iterable

Answer №1

When dealing with an observable, it is essential that your pipe can handle the observable and return one as well. In this case, you will utilize the async pipe in the view. Make adjustments to your pipe as follows:

transform(uos: Observable<IUo[]>, name?: string): Observable<IUo[]> {
  return uos.pipe(
    map(data => {
      if (!data || !name) return [];
      name = name.toLocaleLowerCase();
      return data.filter(uo => uo.title.toLocaleLowerCase().includes(name));
    })
  );
}

Incorporate the template tags accordingly:

<ng-container *cdkVirtualFor="let image of filtered | async" >

TS:

display: Observable<IUo[]>;
filtered: Observable<IUo[]>;

ngOnInit() {
  this.display=this.markerservice.getGeos() 
}

applyFilter2(name : string) {
   this.filtered = this.espipe.transform(this.display,name);
}

DEMO

Answer №2

Consider attempting it this way:

 ngOnInit() {
    this.geoservice.retrieveGeoData().subscribe(response: any[] => {
      this.display = this.transformService.transformData(response, name)
    })
  }

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

The directive does not function properly when used across multiple files

Struggling with @Directives and @Hostlisteners - seeking assistance The directive added to the input seems unresponsive, failing to trigger any events or console.log(). I'm puzzled and frustrated as there appears to be a missing piece of the puzzle t ...

Challenges transitioning syntax from Firebase 4 to Angularfire2 in Angular 4

Currently, I'm in the process of updating my Angular 2.3.1 and Firebase 2.x.x project to the newest version. However, I'm encountering difficulties with syntax and imports. I've been exploring resources like https://github.com/angular/angula ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

The solution to accessing a global variable within the onerror event of an audio object

My goal is to retrieve the value of the isDisabled variable from within the audio.onerror function and then reset it, but I am encountering difficulty in achieving this. public isDisabled: boolean = false; private verifyPrompt(url: string): boolean{ ...

Managing TypeScript objects

Just starting out with TypeScript and feeling a bit lost. The data I receive from my BackEnd looks like this: { "A": [ { "fieldA": 0, "fieldB": "A", "fieldC": ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Can you explain the significance of having two consecutive => symbols?

While I understand lambdas and function types, I am unsure about the following expression: displayFunc: (string) => string = x => x; I find the two symbols "=>" puzzling. Can someone explain what this means? ...

"Error message: Trying to import a component in Angular, but encountering a message stating that the component has no exported

When creating a component named headerComponent and importing it into app.component.ts, an error is encountered stating that 'website/src/app/header/app.headerComponent' has no exported member 'headerComponent'. The code for app.headerC ...

Encountering an issue with Angular 12 where a TypeError is being thrown, specifically stating "Cannot read properties of null (reading 'length') at

I encountered an error message while making a http request in my Angular Service. Strangely, this error only occurs after I logout, but it disappears upon logging back in: Below is the code snippet of my authentication Service: import { Injectable } from ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

Sorting array of arrays in TypeScript and Node.js involves defining the arrays and then applying a sorting algorithm

Recently delved into TypeScript with limited JavaScript knowledge just a couple of weeks ago. I am attempting to scan through all the files in a particular directory, gather each file name (string) and modification time (number>), then organize them in ...

Testing Angular with Jasmine: The spy should have been called as expected

Seeking assistance for a persistent issue that has been troubling me. I am currently working on unit tests for a component I developed, and no matter what I try, I can't seem to resolve the recurring problem of an "Expected spy getTopRatedMedia to ha ...

What is the best way to incorporate sturdy data types into the alternative function for this switch statement

const switchcase = (value, cases, defaultCase) => { const valueString = String(value); const result = Object.keys(cases).includes(valueString) ? cases[valueString] : defaultCase; return typeof result === 'function' ? result() : r ...

Jasmine: utilizing unit test to spy on the invocation of a nested function

When running unit tests for an Angular app, I need to spy on a function called func1 to check if it is being called. However, within func1 there is a call to func2 and I also want to spy on that to see if it is being called. How should I structure my unit ...

Confusing unit testing leads to errors when using Jest

I'm currently tackling two very similar test cases where I need to confirm that two NgRx effects are returning a stream of booleans. While everything is running smoothly in the first test case, I'm encountering difficulties with the second one. N ...

Sending the id from a component to a service in Angular

In my current project, I am working on a chat application using Angular with WebSocket integration. Let me provide an overview of the architecture I have designed for this project. I created a module called 'chatting' which contains a list of use ...

The service does not fall within the 'rootDir' directory in the Angular secondary module

Encountering an error while compiling an Angular library related to the rootDir of sub libraries library/services/src/public-api.ts:31:15 - error TS6059: File 'C:/libname/library/services/src/orders/orders.service.ts' is not under 'rootDir& ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...