Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing?

Below is the code snippet: HTML

     <div *ngIf="tempThermometer | async as temp; else loading">
        <ng-container *ngIf="temp.length !== 0; else noItems">
          <div *ngFor="let item of temp">
            {{temp.sensor}}</div>
        </ng-container>
        <ng-template #noItems>No Items!</ng-template>
      </div>
      <ng-template #loading>loading animation...</ng-template>

TYPESCRIPT

 tempThermometer = new BehaviorSubject<any>([]);
async retrieveData() {
    this.subscription = await this.global
      .getData(`/conditions/latest`)
      .pipe(take(1))
      .subscribe((res: any) => {
        this.tempThermometer.next(Object.values(res['data'].map((obj: any) => {
          return {
            ...obj,
            spinning: true
          };
        })));

        console.log(this.tempThermometer.value);
  });

}

I am trying to show the loading animation while fetching data.

The issue I am facing is that the loading animation does not display automatically; instead, it instantly shows "No Data!".

Answer №1

Your problem lies in the initialization of the BehaviorSubject with [], causing *ngIf="tempThermometer | async to always evaluate to true. You need to specifically check for a length of 0, although it seems you already have a condition to display No Items!

Consider implementing the following changes:

<ng-container *ngIf="!tempLoading">
 <div *ngIf="tempThermometer | async as temp">
    <ng-container *ngIf="temp.length !== 0; else noItems">
       <div *ngFor="let item of temp">
         {{temp.sensor}}
       </div>
     </ng-container>
     <ng-template #noItems>No Items!</ng-template>
  </div>
</ng-container>
<div *ngIf="tempLoading">loading animation...</div>
tempLoading = false; // introduce new variable to toggle loading state, initialize as needed
tempThermometer = new BehaviorSubject<any>([]);
getRoomList() { // remove async from function signature
    this.tempLoading = true;
    this.subscription = this.global
      .getData(`/conditions/latest`)
      .pipe(take(1))
      .subscribe((res: any) => {
        this.tempThermometer.next(Object.values(res['data'].map((obj: any) => {
          return {
            ...obj,
            spinning: true
          };
        })));
        this.tempLoading = false; // update loading state
        console.log(this.tempThermometer.value);
  });
}

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

Having trouble getting the Next.js Image component to work with Tailwind CSS

Recently, I've been working on transitioning a React project to Next.js and encountered some issues with the next/Image component that seem to be causing some problems. <div className=" flex flex-col items-center p-5 sm:justify-center sm:pt-9 ...

Dealing with Angular: unresolved promise error occurring with the utilization of pipe and mergemap

Recently, while working on my Angular 6 project, I came across the concepts of pipe and mergemap, which intrigued me. Essentially, I have a scenario where I need to allow the user to choose between two different CSV files stored in the assets folder. The d ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Attempting to save the result of a fetch call into a variable for the purpose of rendering it as a list in a

I'm attempting to fetch the top 5 NFT collections based on volume and display them in a table format. However, I'm facing an issue where the data is not being mapped correctly and when I click the "get" button, all content on the webpage disappea ...

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

Need help with creating a unit test for the Material UI slider component? An error message saying "Error: Cannot read property 'addEventListener' of null" is displayed when trying to render the component

Encountered a problem while testing the Material-UI Slider with React-Test-Renderer: Uncaught [TypeError: Cannot read property 'addEventListener' of null] Codesandbox Link import React from "react"; import { Slider } from "@materi ...

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

Tips for preventing the inner surface from appearing transparent in WebGL

I am working with the code snippet provided below. The issue I am currently facing is that one side of the partial sphere is non-transparent, while the other side remains transparent. How should I modify the code to make both sides non-transparent? Thank y ...

Switching between tabs in Ionic3, the active tab transitions from displaying text to showing

I have captured a screenshot of my tabs on both iOS and Android versions. I am looking to implement a functionality where, upon clicking the last tab (tab4Root), the icon changes to show a shopping cart. tabs.html <ion-tabs color="danger"> <io ...

Harnessing the Power of Script Loader in Your webpack.config.json File

I'm taking my first steps into the webpack world with Vue.js and vueify for ES6 modules. I've run into a challenge when it comes to loading third-party jQuery plugins. I've successfully used the ProvidePlugin to load jQuery. plugins: [ ...

Setting up Electron with React and TypeScript: A Comprehensive Guide

I've been developing an app using Electron, React (jsx), and Babel. However, I recently made the switch to TypeScript and I'm struggling to get everything functioning properly. The npm packages I've tried only work for either React or TypeSc ...

Divergent functionality of regular expressions in Internet Explorer and Chrome when handling white spaces

Here is a function that validates input by checking for numbers and no spaces in between: checkInputValidity: function() { var isValid = true; var idNumber = this.getView().byId("iDNumber"); var regex = /^[0-9]+$/; if (idN ...

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that. $(window).load(function() { var randomImages = [&apo ...

Is it feasible to create a doughnut chart with curved edges?

My goal is to create a doughnut chart, but my search for reliable CSS/SVG/Canvas solutions has not been successful. https://i.sstatic.net/Rq6Lx.jpg I want each segment to have fully rounded corners, which presents a unique challenge. ...

Failed to transfer form data to server using ajax in Node.js

I am attempting to utilize AJAX to send form data to a Node.js server. I had previously inquired about this on the following post. Below is a glimpse of my code: <div id="inputid" style="width: 400px; height:400px"> <p> Kindly input value ...

Can this functionality be accomplished using only HTML and CSS, without relying on JavaScript?

Image for the Question Is it possible to create a zoom functionality using only HTML and CSS, without relying on JavaScript? I need this feature for a specific project that doesn't support JavaScript. ...

Ensure Your Forms Are Error-Free with Jquery Form Validation

Currently working on a registration form that involves the use of credit cards. I have reached the stage of form validation to ensure that users input correct data in the appropriate fields. However, this has led me to ponder whether relying on JQuery for ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...