Tips for displaying a notification about data filtering and loading using the Async Pipe in Angular

Can someone assist me with this issue? I have a code snippet that retrieves characters from an API and allows me to search for specific characters using input.

I am trying to display different messages on my HTML page based on the search results. If no items are found, I want to show "No items found"; if data is loading, I want to display "Loading".

The problem I'm encountering is that the "No items found" message always appears, even when the application has just started and the "Loading" message is not displayed at all. Could someone please help me identify where the issue lies? Thank you in advance.

HTML

<div *ngFor="let character of (characters | async)">
  {{ character.name }}
</div>

<div *ngIf="loading">
  Loading...
</div>

<div *ngIf="!response.length && !loading">
  No items found
</div>

Typescript

public characters: Observable<DifferentCharacter[]>;
public loading: boolean = false;
public response: DifferentCharacter[] = [];

public gettingAndInputCharacters(): void {
const inputSearchItem = localStorage.getItem('inputCharacterValue') || '';

const filterCharacters = (value: string) => {
  return this.charactersService.getAllCharacters(value).pipe(
    map((response) => {
      const characters = response.results.sort((a, b) => {
        return a.name.localeCompare(b.name);
      });
      return value ? characters.filter((character: DifferentCharacter) => {
        const name = character.name.trim().toLowerCase();
        const searchInputItem = value.trim().toLowerCase();
        return name.startsWith(searchInputItem) ||
          searchInputItem.split('').every((char: string, index: number) => char === name.charAt(index));
      }) : characters;
    }),
    catchError(() => of([]))
  );
};

this.form.controls['searchCharacterInput'].setValue(inputSearchItem);

this.form.controls['searchCharacterInput'].valueChanges.subscribe(value => {
  this.loading = true;
  localStorage.setItem('inputCharacterValue', value);
  this.characters = filterCharacters(value).pipe(finalize(() => this.loading = false));
  this.characters.subscribe(value => {
    this.response = value
  })
});

  this.characters = filterCharacters(inputSearchItem);
}

Answer №1

When writing your code, it is important to avoid using the same name for a class variable and a variable used within a function. For instance, naming a class variable "response" and then using the same name in a map((response) call can lead to confusion.

Take a look at this:

this.characters = filterCharacters(inputSearchItem);

It may seem strange because earlier you had:

this.characters = filterCharacters(value).pipe(finalize(() => this.loading = false));

Instead of:

<div *ngIf="!response.length && !loading"> 

You should use:

<div *ngIf="!(characters | async)?.length && !loading">

Also, pay attention to the return type of functions like this:

const characters = response.results.sort((a, b)

The return type should be {name: string}[], not DifferentCharacter[]. This inconsistency could be causing some general issues in your code.

For a demonstration, check out this link: https://stackblitz.com/edit/angular-4fre3k?file=src/main.ts

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 defining the type of any children property in Typescript

Currently, I am delving into Typescript in conjunction with React where I have a Team Page and a slider component. The slider component is functioning smoothly; however, my goal is to specify the type of children for it. The TeamPage import react, { Fragm ...

How to efficiently display nested object data using Angular Keyvalue pipe

I am facing an issue with a particular HTTP request that returns an observable object containing multiple properties. One of these properties is the 'weight' object which has two key values, imperial and metric. While attempting to loop through ...

What could be causing this minimal Angular - WebTorrent configuration to fail?

The setup appears to be quite straightforward. Check out the Webtorrent usage reference here This is how I have my setup: import WebTorrent from 'webtorrent'; @Component({ selector: 'app-root', standalone: true, template: `bla` ...

Can you please tell me the location of the sqlite database file in Ionic 2 Cordova?

Currently, I am working with cordova-plugin-sqlite within the context of angular2 ionic2. Interestingly, despite my efforts, I have not been able to locate the database file anywhere within my project structure. Numerous attempts to resolve this issue by ...

What could be causing the "Failed to compile" error to occur following the execution of npm

Exploring react with typescript, I created this simple and basic component. import React, { useEffect, useState } from "react"; import "./App.css"; type AuthUser = { name: string; email: string; }; function App() { const [user, setUser] = useState& ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

An easy guide to adding animation to an image with just a click using angular-animations

I have a cool animation that currently triggers when the page loads. However, I want to change it so that the image animates on a button click instead. <div [@fadeInDownOnEnter]="'true'"> <img src="https://www.seoclerk.com/pics/5567 ...

What is the best way to incorporate Typescript React Components across various projects?

I'm venturing into developing an npm package that involves several react components implemented with typescript. As a newcomer to react and npm, I apologize if my query seems basic. Despite researching online, there isn't much information on this ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Angular: verifying the presence of any of the ng-content slots supplied

I have a component template that contains several ng-content elements: <div class="form__general"> <ng-content select="[general]"></ng-content> </div> <div class="form__footer"> <ng-conte ...

Creating an overloaded callable interface using TypeScript

The thread on implementing a callable interface provides some helpful information, but it doesn't fully address my specific query. interface lol { (a: number): (b: number) => string // (a: string): (b: string) => string // overloaded wi ...

Discover an alternative to Events by harnessing the power of Observables to effectively listen for dismiss events in Angular Ionic

Currently, I am utilizing Ionic's inline modal feature that is activated by a boolean value. However, after the modal is closed, the boolean does not automatically reset to zero. The Ionic documentation suggests that developers should monitor the ionM ...

Ensuring a precise data type in a class or object using TypeScript

I am familiar with Record and Pick, but I struggle to grasp their proper usage. My goal is to ensure that a class or object contains specific data types such as strings, Booleans, arrays, etc., while also requiring properties or fields of Function type. in ...

There is no matching signature for Type when using withStyles

Struggling to convert my React App to typescript, I keep encountering the error below and cannot decipher its meaning. The app functions perfectly in plain JS. My package version is material-ui@next TS2345: Argument of type 'typeof ApplicationMenu&a ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Exploring the world of dynamic locale with Angular 5 Pipes

My current situation involves having apps created in angular 4 and I am contemplating upgrading to angular 5. After researching how locale is managed in the pipes, it appears that upgrading may not be feasible. It seems that there are two options provided: ...

"Implementing a feature in Angular to display only a single ul element at a time while iterating through a

In the image above, there is an Add Person button. When this button is clicked, a new row labeled Person 1 is created, and this process continues for each subsequent click. At the right end of every row, there is a share icon that, when clicked, should ope ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...