Changing the value of a variable in RxJS filter operator when a certain condition is satisfied

I am facing an issue with my code where the setDischarges method is not being executed if the condition in the filter (!!discharges && !!discharges.length) is met.

loading: boolean;

this.discharge$ = this.dischargeService.getObservable('discharges');
    this.subDischarge = this.discharge$
      .pipe(
        filter((discharges: Discharge[]) => !!discharges && !!discharges.length),
        map((discharges: Discharge[]) => discharges),
      )
      .subscribe((discharges) => this.setDischarges(discharges));

I have attempted to update the loading variable value based on that condition, but it is not working as expected. The issue arises because the code does not subscribe when the condition is not met and therefore cannot execute setDischarges. I need a solution where the loading variable is updated whether the condition is met or not, without affecting the subscription when the condition is not met.

loading: boolean;

this.discharge$ = this.dischargeService.getObservable('discharges');
    this.subDischarge = this.discharge$
      .pipe(
        filter((discharges: Discharge[]) => !!discharges && !!discharges.length 
        ? this.loading = false : this.loading = true),
        map((discharges: Discharge[]) => discharges),
      )
      .subscribe((discharges) => this.setDischarges(discharges));

Answer №1

this.subDischarge = this.discharge$
      .subscribe((discharges) => {
        this.loading = discharges ? true : false;
        this.updateDischargesList(discharges);
      });

Answer №2

If your question is not clear, I will make an assumption that dischargeService refers to a service call and getObservable returns an observable containing the data from your API request. Just like AJAX calls in JavaScript, all API calls in Angular are asynchronous. Therefore, your code should only set the loading boolean after receiving a response from the service call.

To achieve this, you need to subscribe to the observable. Use the subscribe function to capture the response from the service call. Your code should look something like this:

this.loading = true;
this.dischargeSub = this.dischargeService.getObservable('discharges').subscribe(discharges => {
   // This block will only execute upon successful response
   this.loading = false;
   this.setDischarges(discharges);
}, err => {
   // Handle errors here
});

The variable dischargeSub holds a reference to the subscription, which you can use to unsubscribe when making a new service call or when the component is destroyed.

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

Getting an undefined error value in the ionic overlay side menu - what could be causing this issue?

My current challenge involves displaying the overlay side menu. I have written code to achieve this, adding a menu icon in the header that opens the overlay side menu when clicked, and closes it when clicked outside. However, I encountered an issue where ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...

Can you advise on how to generate a key to access an environment.ts value within a *ngFor loop? Specifically, I am trying to locate keys that follow the pattern 'environment.{{region}}_couche_url' within the loop

I currently have a block of HTML code that is repeated multiple times. <!-- Metropolitan Map --> <div> <app-map [name] = "(( environment.metropole_name ))" [layer_url] = "(( environment.metropole_layer_url ))" ...

Top strategies for ensuring integrity in your frontend React game and preventing cheating

After creating a typing speed game, I am now looking to set up a backend system that can save user high scores and generate a leaderboard. However, I'm concerned about potential users faking their highscores. How can I ensure the integrity of the lead ...

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

Expand the div width to the specified measurement horizontally

Is there a way to horizontally collapse a div (container) to a specific width that I can adjust, effectively hiding its content? The collapse effect should move towards the left. <div id="container"> <button type="button" id="myButton"> ...

Adding a fresh data point to Highcharts

Can the highchart line graph be updated every minute without starting from scratch? I want it to add new data points to the existing line, similar to the example shown in this jsfiddle. $(function () { $.getJSON('https://www.highcharts.com/sample ...

Troubleshooting problem with image loading in AngularJS using ng-repeat

Recently delving into using AngularJS in my projects has presented a rather significant issue when utilizing ngRepeat to load thumbnails from a dynamic array into a DIV. While I won't dive deep into the entire application's details here, let me ...

Encountering some problems while trying to use {return this.getAll.get(this.url)} to consume an API within Angular

I am currently delving into the world of Angular and Typescript to interact with APIs. While I have some experience working with APIs in Javascript, I am relatively new to this setup. The issue I am facing revolves around the code snippet below: To tackle ...

Executing HTML code upon reaching the index.php page

I am facing an issue with running a specific code on my website. Here is the code I need to run: <font size='3'><b> <li class="icon-home"> <a href="{U_INDEX}" accesskey="h">{L_INDEX}</a> <!-- BEGIN na ...

First Impressions of Datatables

Is there a way to display a specific range of rows with Datatables initially? For example, showing rows 100-105 only. Does anyone know if this is achievable using the options available? ...

When running the command "ionic capacitor run android", the task of compiling debugJavaWithJavac failed in the capacitor app

After successfully creating an Ionic 6.19.1 application, I incorporated the variables.gradle file and ran the "ionic capacitor run android" command without any issues. Here are the variable details: ext { minSdkVersion = 26 compileSdkVersion = 30 ...

The Slider component in Material UI's API may not properly render when using decimal numbers as steps or marks in React

I am having trouble creating a Material UI slider in my React application. I can't figure out which property is missing. Below is the code for my React component: import * as React from 'react'; import Slider from '@material-ui/core/S ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

What is preventing the dependency injection of AuthHttp (angular2-jwt) into a component?

UPDATE: Success! Problem Solved After much trial and error, I finally discovered the solution to my issue. It turned out that the problem lied in a simple configuration mistake. To rectify this, I made changes to both my package.json (dependencies section ...

Guide on implementing an onClick trigger for an IconButton contained within a TableCell

As a beginner with MaterialUI, I apologize in advance if my question seems too simple. I am currently working on pulling some data, displaying it in a table, with an extra column that includes a button: <TableCell> {<IconButton> <ClearIc ...

Using jQuery to dynamically alter image source based on class modification

I'm facing an issue with my navbar that changes its class when I scroll down. My goal is to switch the img src when this class changes, but despite searching for solutions in other questions, I haven't found a suitable match yet. Currently, I am ...

Learn how to implement Redux login to display the first letter of a user's name and their login name simultaneously

I am implementing a Redux login feature and after successful login, I want to display the first letter of the user's name or email in a span element within the header section. Can anyone provide a solution for this? Below is my Redux login code snippe ...

A clever way to transfer the "HTML SELECT VALUE" to a different webpage using ajax without the need to refresh the page

Having trouble sending a selected value to another webpage without refreshing? I tried using ajax but couldn't get it to work. After the alert, it seems to stop functioning. Here's the script in one file, where I'm trying to send values 0, 2 ...