Utilizing Observables in a method with multiple if-conditions

There have been multiple instances where I encountered difficulties in implementing a more reactive approach, especially when trying to figure out how to make a method return an Observable in a clean manner.

Here is an example of the code snippet:

public updateItemEligibility(item: Item): void
{
        this.updateCalculations(item);
        if (item.status == Status.Full)
        {
            this.markEligibleItem(item);
        }

        if (item.quantity > 0 && item.Stage == 1)
        {
           const info: ItemInfo =  this.getAdditionalInfoFromApi(); // will use observable
           if (info.Staged)
           {
               this.updateStagedCalculations(item);
           }
        }

        if (item.quantity == 0 && item.Stage == 2)
        {
           const stagingInfo: StagingInfo =  this.getStaginInfoFromApi();
           item.eligible = this.allowStagedItems && item.amount > 0 && stagingInfo.Stages[item.stage].Completed == true;
        }
        this.updateTotals(item);
}

One significant issue here is the necessity to call the API only when specific conditions are met.

Answer №1

If your query is about finding a method that generates an Observable to signal when the item undergoes an update, then the suggested approach is outlined below (comments are included to clarify the process)

 public updateItemEligibility(item: Item): Observable<Item> {
    // Initial steps likely involve synchronous operations
    this.updateCalculations(item);
    if (item.status == Status.Full) {
      this.markEligibleItem(item);
    }
    // Let's move on to the conditional checks.
    if (item.quantity > 0 && item.Stage == 1) {
      // Here, we aim to return an Observable that alerts post the completion of getAdditionalInfoFromApi
      // Leveraging the map operator to ensure notification with item as the value
      // after all necessary actions are taken
      return this.getAdditionalInfoFromApi().pipe(
        map((info: ItemInfo) => {
          if (info.Staged) {
            this.updateStagedCalculations(item);
            this.updateTotals(item);
            return item;
          }
        })
      );
    }
    // Next, we have the second conditional check
    if (item.quantity == 0 && item.Stage == 2) {
      // Similar to the above, we generate an Observable that signals completion of getStaginInfoFromApi
      // (assuming it returns an Observable) and utilize map
      // to notify with item as the value
      return this.getStaginInfoFromApi().pipe(
        map((stagingInfo: StagingInfo) => {
          item.eligible =
            this.allowStagedItems &&
            item.amount > 0 &&
            stagingInfo.Stages[item.stage].Completed == true;
          this.updateTotals(item);
          return item;
        })
      );
    }
    // Should none of the above conditions apply, an
    // Observable that instantaneously notifies with item as the value is returned
    // using the of function
    this.updateTotals(item);
    return of(item);
  }
}

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

Vercel is encountering difficulty locating a module or type declaration during the construction of a Next.js application

Currently, I'm facing an issue while trying to deploy a Next.js app to Vercel. The package react-swipeable appears to have its own type declarations but the build fails with the following error: Running "npm run build" ... > next build ... Failed t ...

Protractor end-to-end tests fail to run properly when the `--spec` flag is utilized

Currently, I am running 'ng e2e' on an Angular CLI project and I am looking to specify a specific test to run instead of running all of them. When I execute ' ng e2e --aot ', the test runs smoothly. However, when I try ' ng e2e ...

Customizing the Position of Material UI Select in a Theme Override

I'm trying to customize the position of the dropdown menu for select fields in my theme without having to implement it individually on each select element. Here's what I've attempted: createMuiTheme({ overrides: { MuiSelect: { ...

ngx-upload-core and media files

Recently, I started working with the newest release of ngx-resource-core in Angular 7. I'm wondering if there is a method to submit a multipart form when considering that a model could include files or byte arrays? ...

What is the process of creating the /dist folder in an unreleased version of an npm package?

Currently working on implementing a pull request for this module: https://github.com/echoulen/react-pull-to-refresh ... It seems that the published module generates the /dist folder in the package.json prepublish npm script. I have my local version of the ...

Having trouble utilizing the ng-Command in Angular?

Currently, I am attempting to set up Angular in a vagrant-box environment. npm install -g @angular/cli Unfortunately, I encounter an error while trying to use the client: The program 'ng' is currently not installed. You can install it by typin ...

Having trouble installing plugins on Ionic 6. Every time I try, an error pops up. Any suggestions on how to proceed?

Failed to fetch plugin https://github.com/katzer/cordova-plugin-background-mode.git via registry. It seems like there is a connection issue or the plugin specification is incorrect. Please check your connection, as well as the plugin nam ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

Best practices for incorporating CSS and JS files into an Angular deployment

I am currently in the process of integrating an Admin Template that I previously used in a traditional PHP application into a new Angular project. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel= ...

Customizing the Android Back Button behavior in NativeScript for a single specific page

I am currently using NativeScript version 5.2.4 along with TypeScript. My goal is to disable the back button functionality in one specific page only, but I'm facing an issue where it also disables the back button behavior for child pages. Below is the ...

Error: Select dropdown placeholder malfunctioning

Even after trying numerous solutions from various forums, I am unable to make the placeholder display in my code. Maybe a fresh perspective can help spot what I might be missing. view image here I have experimented with using "" as the value, as ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Using TypeScript to wrap a class with a Proxy object

I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running i ...

Description of how to define rows and columns for a Quasar QTable using TypeScript

Just curious if there is a Typescript definition available for the rows and columns of Qtable? Appreciate any help on this. Cheers, marnold ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

Node.js/TypeScript implementation of the Repository design pattern where the ID is automatically assigned by the database

Implementing the repository pattern in Node.js and Typescript has been a challenging yet rewarding experience for me. One roadblock I'm facing is defining the create function, responsible for adding a new row to my database table. The interface for ...

Step-by-step guide for resolving the issue of "Observable.share is not recognized as a function" in Angular 2

When working with cache structure in Ionic 2, I often encounter an error when defining an observable array to store data retrieved from the server. How can I troubleshoot this issue and resolve it? marketArray : Observable<any>; /* GLOBAL */ th ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...