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.

https://i.sstatic.net/XW6sU.png

Here is the response data:

https://i.sstatic.net/oVLQc.png

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

Submit numerous queries to verify the presence of a name and assign it to the name attribute

I have a collection of unique devices. As part of a process, I need to assign a default name to each device ("DeviceX" - where X is a sequential number), but some of the names may already be in use. To handle this, I must make a request to check ...

WSO2 PayloadFactory is delivering JSON data neatly packaged in a JSONObject

Currently, I am utilizing WSO2 API Manager 1.7.0 and experimenting with a simple payloadfactory to switch a call from a GET to a POST while passing in a json payload. In analyzing the log files, it seems that WSO2 is sending the json enveloped within {"js ...

Unable to run unit tests on project using my custom React library

If any of you have encountered this issue or know how to solve it, please help me. I created an NPM package that can be found at https://www.npmjs.com/package/@applaudo/react-clapp-ui It installs and runs smoothly in other projects using create react app; ...

Efficiently configuring Angular 2 with ng-bootstrap

Hi there, I am currently diving into the world of Angular and Bootstrap, while also exploring node js. My goal is to create a solid foundation using the webpack starter kit available at this link: https://github.com/AngularClass/angular2-webpack-starter ...

The width of mat-table columns remains static even with the presence of an Input field

I'm currently working on an Angular component that serves the dual purpose of displaying data and receiving data. To achieve this, I created a mat-table with input form fields and used {{element.value}} for regular data display. Each column in the tab ...

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. ...

After performing the `ng build --prod` command in Angular 4, deep linking functionality may not

I have a requirement to display different screens in my Angular application based on the URL pasted by the user in the browser: http://localhost/screen1 (should show screen1) http://localhost/screen2 (should show screen2) To achieve this, I have set up ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Tips for activating scroll feature for certain section of an HTML page

For the styling of my page, I'm utilizing Scss and am facing an issue related to setting up scrolling for specific sections of an HTML page. You can check out the image reference here. During a scroll event, I want to ensure that the Categories (left ...

Tips for implementing server-side pagination using NestJS

Working with a MEVN stack that includes Nestjs, MongoDB (mongoose), I am currently tackling the task of setting up server-side pagination. I've decided to utilize mongoose-aggregate-paginate-v2 for this purpose, but so far, I haven't been able to ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

Contrasting the Appmodule and Pages module within Angular: A Comparison

After cloning this project, I noticed that it contains two types of modules: one inside the page and the other in the root directory. Directory Tree: https://i.sstatic.net/tjq0I.png App.module.ts import { BrowserModule } from '@angular/platform-bro ...

Retrieve() displays solely the initial array within an object

I am facing an issue with my Redux/React project where I am calling an API to search for a specific ID based on the useParams value. I suspect the problem lies in my return statement return data.hero.find(hero => <Hero key={hero.id} hero={hero} /> ...

Value attribute property binding

Currently, I am diving into the world of Angular 5 and focusing on grasping the fundamentals. One concept that caught my attention is template reference variables. However, I encountered a roadblock along the way. Instead of utilizing a template reference ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Tips for incorporating ngIf within a td element

My dilemma is with a table I have that displays data from a database. I need to be able to edit the data based on certain qualifications, so I want to include two buttons - one for deleting and one for editing. These buttons should only be enabled if the r ...

The type 'MutableRefObject<undefined>' cannot be assigned to the type 'LegacyRef<HTMLDivElement> | undefined'

I have created a customized hook that takes a ref object and observes its behavior: import { useState, useEffect, MutableRefObject } from "react"; const UseOnScreen = (ref: MutableRefObject<undefined>) => { const [isIntersecting, setI ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

What is the best way to maintain the index of a for loop when incorporating AJAX to insert PHP data into an object?

Hey there, I'm diving into the world of AJAX and PHP implementation. I've hit a bit of a roadblock lately as I feel like I might be missing a simple solution. Currently, my code fetches data from a trove API using PHP, and for each item it appen ...