Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query.

let request = this.http.post(this.searchlUrl, payload).pipe(
          retryWhen(errors => errors.pipe(delay(1000), take(2), concat(throwError("Error Data")))), 
          map( res => {
            // If the response contains an empty 'hotels' array, I want to force an error
            return res; 
          })
        ).subscribe(res => {
            // Perform actions when everything is ok
        }, err => {
            // Handle errors here
        });

I am utilizing retryWhen to initiate a new request in case of errors (with a 1-second delay). My current approach involves triggering an error upon receiving an empty result to activate the retry mechanism. However, I need guidance on how to achieve this and determine the best practice for forcing a re-query when encountering an empty response.

Answer №1

The issue at hand is the sequencing of operators. The retryWhen method only responds to error notifications, so you must throw the error before calling retryWhen:

this.http.post(this.searchlUrl, payload).pipe(
  map(response => {
    if (something) {
      throw new Error(); // This will be caught by `map` and emitted as an error notification.
    }
    return response;
  }),
  retryWhen(errors => errors.pipe(take(2), delay(1000))),
).subscribe(...);

Check out the live demonstration here: https://stackblitz.com/edit/rxjs-cmh1wd

Answer №2

Check out this simple illustration of a retry scenario that could provide some guidance. The example uses the of method to generate the observable stream. You can modify it to fit your specific API call.

private responseToDisplay: string[] = [];

  ngOnInit() {
    var request = 
      of(this.responseToDisplay).pipe(
        map(response => {
          if (response.length === 0) {
            this.responseToDisplay.push("new value");
            console.log("No data received!")
            throw new Error();
          }
          return response;
        }),
        retryWhen(errors => {
          console.log("Retrying the operation!")
          return of(this.responseToDisplay)})
      );

      request.subscribe(data => console.log(data[0]));
  }

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

Employ the use of expressions to retrieve and store input values within a template

<input ngModel name='quantity' placeholder='Quantity' type="number" class="form-control" pattern="^\d*(\.\d{0,2})?$" required /> <input ngModel name='price' c ...

Angular 11 issue: Unable to display image on the webpage

When I try to view my image by directly using the URL in the src tag, it works fine. However, when I attempt to load it dynamically, an error is thrown. Even using [src]="img.ImagePath" method gives me the same response Here is the error logged ...

Error: The function jquery_1.default is not recognized by webpack

I am encountering an issue with using external imports of jQuery in webpack. Despite trying different import syntaxes such as import $ from 'jquery', import * as $ from 'jquery, and const $ = require('jquery'), I continue to receiv ...

Using @ViewChildren in Angular 2 for creating recursive components

I am working on a recursive component that showcases tag A. Firstly, there is the parent component - HTML <div class=" suggestions" style="display : inline-block;" tabindex=-1 #autocompleteDiv> <span style="width: auto;cursor: pointer;posit ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

What's the process for deducing the default generic parameter from a function type?

Is there a way to extract the default type parameter of a function in order to make this statement compile successfully? const fails: string = "" as ReturnType<<T = string>() => T>; ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Is there a way to access every item that includes a particular attribute and attribute term within the woocommerce-rest-api?

Struggling to retrieve products that have the "x-attribute" and "x-attribute-term" using Node.js with the WooCommerce REST API library from here. I've explored solutions on stackoverflow and other sites but none seem to work. Atte ...

Dealing with Cross-Origin Resource Sharing Problems in Angular 8 REST API

I am currently working with 2 components: The first component, "CurrenciesComponent," is being loaded. @Component({ selector: 'app-currencies', templateUrl: './currencies.component.html', styleUrls: ['./currencies.componen ...

Reduce the size of log messages in cypress

I am looking to shorten the cypress messages to a more concise string, for instance: Cypress log Transform to: -assert expected #buy-price-field to have value 17,169.00. Is there a way to achieve this? I have searched through the documentation but hav ...

Fixing the issue of the Put method not successfully updating MongoDB when using Angular7 with NodeJS on the

Currently, I am facing an issue with my Angular7 application that is connected to NodeJS and MongoDB on the backend. After testing the put method using Postman, it seemed to work perfectly. However, the problem seems to be within the Angular service compon ...

Having trouble with GoogleSignIn in React Native Firebase app

During the development of my React Native App, I integrated Firebase as the Authentication System. The app compiled successfully, but upon attempting to use the GoogleSignIn method, an error message appeared on the AndroidToast: "Se ha producido un error. ...

Unable to locate the API compiler-cli and the VERSION function

After downloading a repository from GitHub to run an Angular project, I typically use the command npm install to add node modules to the project. However, when I then attempt to run ng serve, I encounter the following error: https://i.stack.imgur.com/xiqo ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Determining the sequence of events for @HostListener event within an Angular directive

I am facing an issue with my Angular 9 application wherein a parent component contains a child component (referred to as "overview") which has a button. Upon clicking the button, the child component emits an event that should be handled by the parent compo ...

Running tests on functions that are asynchronous is ineffective

Recently, I made the switch from Java to TypeScript and encountered a challenging problem that has been occupying my time for hours. Here is the schema that I am working with: const userSchema = new Schema({ username : { type: String, required: true }, pa ...

Angular 2: A guide to resetting dropdown and text values when changing radio button selections

When the user interface displays two radio buttons - one for YES and one for NO - and the user clicks on YES, a dropdown is shown. Conversely, if the user clicks on NO, a textbox is displayed. How can I clear the values in the dropdown and textbox when s ...

Consolidating Typescript modules into a single .js file

Recently, I was able to get my hands on a TypeScript library that I found on GitHub. As I started exploring it, I noticed that there were quite a few dependencies on other npm packages. This got me thinking - is there a way to compile all these files int ...

Retrieving User's Theme Preference from Local Storage in Next.js Instantly

As mentioned in various other responses, such as this one, Next.js operates on both the client and server side, requiring a guard to properly fetch from localStorage: if (typeof localStorage !== "undefined") { return localStorage.getItem("theme") } else ...

Implementing conditional properties in Typescript based on the value of another property

Is it possible to make a property required in a type based on the presence of another property? Here's an example: type Parent = { children?: Child[]; childrenIdSequence: string[]; // This property should only be required when `children` is prov ...