Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to reappear if no results are found. Ideally, I would like "No Results Found" to display only after a search query has been triggered and evaluated. Is there a more effective way to achieve this rather than using a timeout method? Below is the function code I have implemented:

public get noResultsFound(): boolean
{
    if (this.query && !this._isSearching && !this.hasResults) {
        return true;
    }
}

Below is how I have structured my view code:

<div *ngIf="inputHasFocus && noResultsFound" class="no-results-found">No Results Found</div>

Answer №1

Looking for a solution? Promises might be the answer! 😄 Check out this link for more information on Promises.

Here's a simplified version of how you can use promises in your code:

search = (paramObj): Promise<SomeDataClass> => {
    // Your search logic goes here
}

requestSearch() {
    this.search(null).then((result) => {
        if (result.length === 0)
        {
            // Handle case when there are no results
        }
        else{
            // Show the results here
        }
    })
}

If you want to see a more comprehensive example, check out this snippet:

class example {
    public someBool = false;

    public search = (paramObj): Promise<Array<string>> => {
        this.someBool = !this.someBool;
        return new Promise<Array<string>>((resolver) => {
            // Simulating a time-consuming operation
            setTimeout(() => {
                if (this.someBool) {
                    resolver([]);
                } else {
                    resolver(["hi","there"]);
                }
            }, 1000)
        });
    }

    public requestSearch() {
        this.search(null).then((result) => {
            if (result.length === 0) {
                console.log("No results found")
            }
            else {
                console.log(result)
            }
        })
    }
}

Answer №2

By making a simple adjustment to the function's logic, I was able to avoid the need for a debounce timeout and prevent the premature triggering of "No Results Found". Here is the updated code snippet that resolved the issue:

public checkForNoResults(): boolean
{
    if (!Object.isNullOrUndefined(this._results) && this._results.length < 1) {
        return true;
    } 
}

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

Utilizing flot.js to showcase a funnel chart with an external JSON file as the data source

Trying to create a funnel chart using the Flot.js library with an external JSON file as input. The JSON file is being fetched successfully, but the chart is not being plotted. [ { "data": 10, "label": "a" }, { "data": 81, "label": "b ...

Issue with TableHead not functioning properly when sorting is requested

I'm currently facing an issue with my table that has clickable row headers for sorting functionality using the onRequestSort function. Unfortunately, it seems like this feature is not working as expected. I have implemented the sorting logic using rea ...

Increase the size of the embedded iframe in your Cordova application by using the pinch-to-zoom

I have been struggling with this issue for the past few days and am having trouble finding a solution.. I am trying to figure out how to embed an iframe in a cordova app (running on an iOS device) to display an external webpage while allowing users to pin ...

Creating Excel documents using Angular and XLSX template generator

In my Angular application, I am utilizing the XLSX library to manipulate an Excel file. The file I start with is encoded in base64 format, so my first task is to decode it, make some changes to specific cells, and then save the modified file back in base64 ...

Trigger an event in Vue with specified parameters

I am attempting to emit a function with parameters in the following way. template: ` <div class="searchDropDown"> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup=" ...

Requesting a resource using the HTTP GET method returned no data

Looking to process the response from an http-request using JavaScript? Check out this straightforward example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

Ways to retrieve a JSON element and incorporate it into a CSS styling

Can someone assist me in converting a JSON object for use in CSS? I've attempted to do this using Vue.js, creating a map legend with v-for to generate the legend. However, if there is an alternative method that allows me to take a JSON object and ins ...

Encountering the "Local resource can't be loaded" error when attempting to link a MediaSource object as the content for an HTML5 video tag

I'm attempting to make this specific example function properly. Everything runs smoothly when I click the link, but I encounter an error when trying to download the HTML file onto my local machine and repeat the process. An error message pops up sayi ...

Tips on rearranging the location of a div element within a directive

I have created a custom directive that displays two divs, Div1 and Div2, with a splitter in the middle: Splitter Image Now, I am looking for a way to swap the positions of these two divs dynamically using an Angular directive. I thought about using ng-swi ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

`The process of adding an element to the beginning of an array``

I find myself in this scenario: I am dealing with 2 array1 variables, defined as array1 = ["fruit","vegetables"]; and array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"]) T ...

Encountering an "ionic 4 frame-ancestors *" error while attempting to watch a Twitter video

Currently, I am in the process of developing a news app using Ionic 4. I recently tackled the challenge of embedding tweets in Twitter cards successfully. However, a new issue has arisen. When a tweet includes a Youtube video, everything works perfectly ac ...

fusion of Angular and ASP.NET Core

When working with asp.net core and angular, my current process involves: Creating a client app using angular cli Developing an asp.net core mvc app Connecting the two using Microsoft.AspNetCore.SpaServices.Extensions (spa strategy = proxy) Modifying the I ...

Failure of Ajax to populate dropdowns in Internet Explorer

I've been grappling with some code for the past couple of days and I'm stuck. I really need some help. Here's what I'm trying to achieve: Manually fill the first dropdown menu Retrieve the selected value from the first dropdown, use i ...

Obtaining data from a TypeScript decorator

export class UploadGreetingController { constructor( private greetingFacade: GreetingFacade, ) {} @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: (req: any, file, cb) => { if (process.env ...

Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality. Can someone guide me on how to retrieve an image value and send it to my server? Edit: I have experimented with dec ...

Creating a personalized 404 page in your Angular Project and configuring a route for it

I am currently working on an Angular project that includes a component named 'wrongRouteComponent' for a custom 404 page. Whenever a user enters a non pre-defined route, the 'wrong-route.component.html' should be displayed. However, I a ...

The Cross-Origin Request has been blocked due to the Same Origin Policy prohibiting access to the remote resource. The reason for this is that the CORS preflight response was unsuccessful

SERVERSIDE // Establishing Headers app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers ...