Display "No Results Found" in Angular and Ionic 4 when the observable is empty

Below is the HTML code:

<ion-list>
    <ion-radio-group>
      <ion-item class="ion-no-padding" *ngFor="let service of services | async">
        <ion-label>
          <ion-grid>
            <ion-row>
              <ion-col size="12">
                {{ service.name }}
              </ion-col>
            </ion-row>
          </ion-grid>
        </ion-label>
        <ion-radio slot="end" value="{{ service.id }}"></ion-radio>
      </ion-item>
    </ion-radio-group>
  </ion-list>

and my page.ts contains the following code:

services: Observable<Service[]>;
// db service connecting to firebase
  ngOnInit() {
    this.services = this.db.getServicesFromVenue(this.routeParams.venueID);
  }

Service code:

  getServicesFromVenue(venueID: string): Observable<Service[]> {
    this.serviceCollection = this.afs.collection<Service>('services', ref => ref.where('venue', '==', venueID));
    return this.services = this.serviceCollection
      .snapshotChanges()
      .pipe(
        map(actions => {
          return actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        })
      );
  }

Everything works well, but I am struggling to display a message "no services" when there are no results. I have tried various methods but nothing seems to work:

  <ion-list *ngIf="services | async as service; else noServicesBlock">

This code snippet gives me no output. Any help would be appreciated. Thank you in advance!

Answer №1

To begin, you can initialize with a null value by using startWith(false) to display the noServicesBlock. Make sure to include a condition check to determine if the actions array is empty (an empty array will evaluate to true []) and return a false value in that case.

retrieveServicesFromLocation(locationID: string): Observable<any> {
    this.serviceCollection = this.afs.collection<Service>('services', ref => ref.where('location', '==', locationID));
    return this.services = this.serviceCollection
      .snapshotChanges()
      .pipe(
        map(actions => {
          if(!actions.length) return false;
          return actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        }),
        startWith(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

Retrieving the type of a mapped property using the TypeScript compiler API

If I have a type Mapping = Record<'success' | 'error', React.ReactNode>, how can I extract the TypeScript type using the compiler API? While the symbol for Mapping has the expected two properties, the symbol for each property doe ...

Updating from Angular version 12.0.4 to 12.1.0 results in a runtime error. As a temporary solution, we are reverting back to version 12.0

There is a related issue discussed here: Angular: TypeError: Cannot read property 'firstCreatePass' of null However, the problem in that case pertains to different Angular versions and the solution provided did not resolve my issue. The recurring ...

Suddenly encountered issue when working with TypeScript Interfaces while integrating Quicktype 'allOf'

Our transition from using JSON Type Definition to JSON Schema includes the utilization of Quicktype to convert JSON Schemas into TypeScript Types. While Quicktype has been effective in most cases, it seems to struggle with converting Discriminators and mor ...

Utilizing a single component for various purposes with diverse tags in react

I am faced with the challenge of creating two almost identical components, Component A: const ClaimedLabel = ():React.Element => ( <div tw=""> <p tw="">Some Text here</p> <div tw=""> <Icon ...

Angular7 & Bootstrap4: Creating a collapsible navigation bar

Currently, I am working on creating a navbar with a collapsible animation that functions properly on mobile screen sizes. I have been following a tutorial which has guided me in the right direction: . Although I have successfully implemented the functiona ...

Class with an undefined function call

Currently, I am working with angular2 and TypeScript where I have defined a class. export class Example{ //.../ const self: all = this; functionToCall(){ //.. Do somerthing } mainFunctionCall(){ somepromise.then(x => self.fu ...

The directive for accepting only numbers is not functioning in versions of Chrome 49.xx.xx and earlier

I have implemented a directive in Angular 6 to allow only numbers as input for certain fields. The directive code is shown below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[NumbersOnly]& ...

Issue with next.handle not functioning properly in Angular 8 when re-requesting

In the code snippet below, the issue is that even after the token expires (401), the API for fetching the refresh token is called, but the request is not re-sent with the updated token using the inner next.handle(). export class InterceptService implements ...

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

Instructions on invoking a function when a button is clicked

I am attempting to trigger a dataUpdate function upon clicking the edit() button I am striving to modify the record Current Version: Angular CLI: 10.0.6 Angular: 10.0.10 https://i.sstatic.net/4MR8P.png registration.component.html <div> ...

Monitoring URL changes in Angular2 using the HostListener

I have a common navbar component that is included in every page of my website. I would like it to detect when the URL changes using a HostListener. @HostListener('window:hashchange', ['$event']) onHashChange(event) { this.checkCu ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6. Let's imagine we have an array of objects: [{ Objec ...

Convert JavaScript to TypeScript by combining prototype-based objects with class-based objects

My current challenge involves integrating JavaScript prototype with class-based programming. Here is an example of what I've tried: function Cat(name) { this.name = name; } Cat.prototype.purr = function(){ console.log(`${this.name} purr`) ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Using static classes with ngClass does not produce the desired effect

I'm currently developing a library using Angular and integrating StoryBook. I encountered an issue where adding a class named "Primary" to the story didn't work, even when added statically in the code. Here is the HTML code snippet: <button [ ...

Exploring the use of Jest for testing delete actions with Redux

I've been working on testing my React + Redux application, specifically trying to figure out how to test my reducer that removes an object from the global state with a click. Here's the code for my reducer: const PeopleReducer = (state:any = init ...

The switch statement and corresponding if-else loop consistently produce incorrect results

I'm currently facing an issue where I need to display different icons next to documents based on their file types using Angular framework. However, no matter what file type I set as the fileExtension variable (e.g., txt or jpg), it always defaults to ...

The Excel file fails to accurately interpret the date after being extracted from a zip folder

When uploading a zip folder containing an Excel file through the UI, I implemented the following code snippet: getZipData(file: File) { const jsZip = require('jszip'); let excelRecord: any[] = []; let images: { path: string, image: string }[] = [ ...

What is the process of extracting information from a JSON file and how do I convert the Date object for data retrieval?

export interface post { id: number; title: string; published: boolean; flagged: string; updatedAt: Date; } ...