Utilizing Angular 4's piping feature to manipulate data sourced from an API observable within

I am currently working on setting up a filter for my stories. After subscribing to the API call, I receive the data in the form of an array of objects. However, I am encountering an error while trying to apply filters. Here is a snippet of relevant information, but I can provide more details if necessary. I am still learning about Pipes in Angular 4, so any tips or advice would be greatly appreciated! Thank you.

Here is the response data:

Pipe Section:

import { Pipe, PipeTransform } from '@angular/core';
import { DiscoverComponent } from './discover/discover.component'


@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  //transform is called every time that the input changes in the filter pipe
  transform(stories: any, term: any): any {
    //check if search term is undefined and return all stories
    if(term === undefined) return stories;
    // return updated storiesarray with filter
    return stories.filter((story) => {
      return story.name.toLowerCase().includes(term.toLowerCase()) //either true or false
    })
  }

}

Component Section:

private getStories(page, hits, feed) {
    feed = this.feed;
    if (this.noSpam || this.page > 0) { //no doubletap feed
      this.noSpam = false;
      this.storiesService.getStories(this.page, this.hits, this.feed)
        .subscribe(
        (data) => {
          console.log(data);
          if (!data || data.hits == 0 || data.hits < 6) {
            this.finished = true;
            console.log("No more hits :(")
          } else {
            this.finished = false;
            // this.data = data;
            for (let story of data.hits) {
              this.hitsArray.push(story);
              // console.log(data)
            }
          }
        })
      setTimeout(() => {
        console.log("Wait 2 seconds before trying to get feed!")
        this.noSpam = true;
      }, this.delay);

      console.log("side: " + this.page)
    }
  }

HTML Section:

<input [(ngModel)]="term" [ngModelOptions]="{standalone: true}" type="text" id="bloody-bird-forms" class="form-control">

And

<div class="col-xs col-sm col-md-4 col-lg-4 story" *ngFor="let story of hitsArray | filter:term">

Answer №1

When dealing with asynchronous data in ngFor, it is important to use the 'async' pipe. Following that, additional pipes can be applied in a specific order. The async pipe should always come first since the execution order is left to right. If you wish to apply a pipe in your controller, make sure to import the pipe and use it like this:

const modifiedString = pipename.transform(originalString);

Answer №2

It appears that the stories variable is either not defined or null. To fix this issue, adjust your pipe code as shown below:

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  // The transform method is called whenever there is a change in the input for the filter pipe
  transform(stories: any, term: any): any {
    // Check if the search term is undefined and return all stories if it is
    if(!stories) return [];
    if(stories && term === undefined) return stories;
    
    // Return the updated array of stories with the applied filter
    if(stories && stories.length > 0){
        return stories.filter((story) => {
            return story.name.toLowerCase().includes(term.toLowerCase()); // Returns true or false
        });
    }
  }

}

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

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Is it possible to utilize Next.js API routes for both a web and mobile application?

I am looking to create a web application using Nextjs and potentially develop a mobile application in the future. Is it possible to utilize the Nextjs API for both the web and mobile versions? Please Note: I cannot use ReactJS due to the requirement for ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...

Creating a versatile JavaScript/TypeScript library

My passion lies in creating small, user-friendly TypeScript libraries that can be easily shared among my projects and with the open-source community at large. However, one major obstacle stands in my way: Time and time again, I run into issues where an NP ...

Tips for resetting a form after submission

Hey there, I'm currently working with Angular 7 and facing an issue with form submission. After submitting the form successfully, I want to reset it without triggering the required validation for input fields. Here's a snippet of my TypeScript co ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

Obtain document via Angular 2

Is it possible to use TypeScript to download an image that is already loaded? <div *ngIf="DisplayAttachmentImage" class="fixed-window-wrapper_dark"> <button class="btn btn-close-window" (wslClick)="HideAttachmentImage()"> & ...

What is the best way to implement an interface for accurately checking each prop type?

Currently, while working with Typescript, I am looking for a solution to define an interface with specific properties inside my object of marks. At the moment, I am using "any", but I know there must be a better approach. Any guidance or advice on how to p ...

Issue with triggering angular function multiple times in certain conditions

Issue: Experiencing difficulties with Angular directive as it is being called multiple times, resulting in incorrect transaction outcomes and multiple entries on the Console screen. Desired Outcome: Ensure that the function executes only once. Sample cod ...

Create a new instance of the parent class in TypeScript to achieve class inheritance

Looking for a solution to extending a base class Collection in JavaScript/TypeScript to handle domain-specific use cases by implementing a "destructing" method like filter that returns a new instance with filtered elements. In PHP, you can achieve this usi ...

The ideal version of firebase for showing messages in the foreground

Looking to instantly display notifications as soon as they are received? I recently watched a video on Angular 8 + Firebase where version 7.6.0 was discussed. While the notification is displayed in the foreground for me, I find that I need to click on some ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Centered title in side menu for Ionic 3

I recently utilized the Ionic CLI to create an Ionic project. The version I am working with is Ionic 3. Currently, I am facing a challenge in centering the title image. Any assistance on this matter would be greatly appreciated. <ion-menu [content]=" ...

Protractor experiencing difficulty recognizing Angular functionality

Recently, I made the switch to using Protractor for running end-to-end tests on my Angular application. However, the e2e tests have suddenly started failing because Protractor is unable to detect Angular on the website. I raised this issue in their GitHub ...

Step-by-step guide to accessing a corrupted Excel file in Angular 8

I have implemented the following code snippet in my project, where I am utilizing , and now I'm seeking a solution to properly set the file path for the filename. import { Component, OnInit } from '@angular/core'; import * as XLSX from &apos ...

What can I do to protect my REST API from unauthorized access?

Recently, I created a straightforward REST API using ExpressJs with React as my client-side application. However, I realized that anyone can access my API endpoints due to the nature of having the React app on the client side. This means others could pot ...

What causes BehaviorSubjects in Angular RXJS to emit multiple values?

click here to see the image descriptionUsing BehaviorSubject for sharing data between components in my app has led to a performance problem caused by multiple emissions of the same value. For example, when I make an HTTP call to fetch a team object from th ...

Distinguishing Between URLs for Google Maps JavaScript API

Can you explain the discrepancy between two Google API URLs? One is https://maps.google.com/maps/api/js?key={api_key}, which is currently not functioning and returns an error when attempting to use it on a map to display coordinates. The other is https:/ ...

Enhancing the internal styling of ngx-charts

While working on the ngx-charts Advanced Pie Chart example, I noticed that the numbers in my legend were getting cut off. Upon inspecting the CSS, I discovered that a margin-top of -6px was causing this issue: https://i.stack.imgur.com/oSho1.png After so ...

Creating a custom data type for the Tanstack table filtering function

I developed a unique filter function specifically for enhancing the functionality of Tanstack Table by utilizing fuse.js. Despite my efforts, TypeScript consistently raises concerns when I try to define the type for my custom function. My goal is to alig ...