Angular and RxJS: Ensuring continuous interval execution in the event of an error

Every 10 seconds, I make a call to a RESTful service through an Angular service called "myservice" and a function called "foo."

 ngOnInit ()
 {
      interval (10000).pipe (startWith (0), mergeMap (obs =>
      this.myservice.foo ())).subscribe (resp =>
      {
        this.data = resp;
      },
      error =>
      {
        console.log ("error");
      }
      );
 }

The current setup works fine when the connection to the REST service is active. However, when the REST service is down, the interval stops as well.

How can I modify the code to keep the interval running, even when the REST service is unavailable?

Answer №1

Have you considered handling errors at the level of the "inner" observable (the one that could potentially generate errors) rather than the entire stream? Perhaps something like this:

ngOnInit () {
  interval(10000).pipe(
    startWith(0),
    mergeMap(obs => this.myservice.foo().pipe(
      catchError((error) => {
        console.log(error);
        return empty(); // or return of(error) and take appropriate action in the subscribe block
      }),
    ),
  )).subscribe(resp => this.data = resp);
}

Answer №2

This response does not directly address the specific situation at hand (I prefer to test solutions on StackBlitz before sharing any code suggestions). However, I have included a screenshot from a video by Ward Bell that discusses effective error isolation methods.

https://i.sstatic.net/2T7Qp.png

Take note of the "wrong way" and "right way" labels above the two code snippets in the screenshot.

You can view this section of the video here: https://www.youtube.com/watch?v=q--U25yPTrA&feature=youtu.be&t=1240

Answer №3

To handle errors, utilize the retryWhen operator

interval(10000)
  .pipe(
    startWith(0),
    switchMap(obs => this.myservice.foo()),
    retryWhen(error => {
      return error.flatMap((error: any) => {
          if (error.status === 503) {
              return Observable.of(true);
          }
          return Observable.throw({error: 'No retry'});
      });
);

Answer №4

Utilize flatMap to map the value to an inner observable that manages errors. Within the inner observable, include a catchError handler in the pipeline to handle errors quietly with an empty observable. See the example below:

interval(10000).pipe(
  flatMap(num => of(num).pipe(
    mergeMap(num => this.myservice.foo()),
    catchError((error) => {
      console.log ("error");
      return empty();
    })
  ))
).subscribe(resp => {
  console.log(resp)
});

Stackblitz

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

Troubleshooting change detection problem in Ionic 3 application

There seems to be an issue with the data not being reflected in the view despite changes in the service and component. Various solutions were attempted to address this issue, but none have proven successful: Utilized the ngDoCheck lifecycle hook Imp ...

When using an Angular2 application that relies on an external reference to Auth0Lock, the application encounters a NotFound error when executed

For my latest project, I decided to create an app using angular2-seed as a base. Everything was going smoothly until I tried deploying the production build on an Azure website. To my surprise, I encountered an issue when trying to load the page: > Refe ...

pattern matching to establish the path for unit test files

Just starting to dive into regular expressions and I've encountered a situation in my test case config file where I need to specify certain files. var webpackConfig = require('./webpack.store1.config.js'); module.exports = function(con ...

What is the best approach for mapping the observable and subscribing to the data before combining it into the mapped result?

I am currently attempting to subscribe to an observable that has been formed through multiple uses of the map operator in order to construct the final result. Let's consider a situation where we have an outer observable function called functionA() th ...

What is the best way to retrieve the final entry from a JSON file while using json server with Angular?

I'm currently working with a JSON file where I am making post requests followed by get requests. My goal is to retrieve the latest record in each get request after submitting a post request. For example: [ { "id": 1, "title&qu ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

Exploring the Implementation of Date/Time Service in Angular 2

My current project involves setting up a simple service in Angular 2. The objective is to have the current date and time displayed when a user clicks a button. However, upon implementing the code provided below, I encountered an error: Error during evalua ...

Steps for adding Node modules to a Nexus private repository

Running my organization's private Nexus npm repo, all packages are installed on my local machine through the internet. I want to store all packages on my Nexus private repo and have successfully uploaded them using the npm publish command. However, wh ...

A data type that exclusively accepts values from an enumerated list without mandating the inclusion of every possible value within the enum

Here's a code snippet I'm working with: enum Foo { a, b, c } type Bar = { [key in keyof typeof Foo]: string; } const test: Bar = { a: 'a', b: 'b' }; I'm encountering an issue where the code is complaining ...

Displaying data labels overlaid on top of data points in line charts

Currently, I am utilizing Angular2 along with ng2-charts to generate a line chart. My objective is to position the data labels directly above the points, similar to how they appear in the bar chart showcased in this image: bar chart I stumbled upon the ch ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Is it possible to utilize useEffect for verifying the existence of the user token within the localStorage?

I am in the process of developing a web application that requires authentication. I am wondering if it is effective to create a private route by adding a condition in the useEffect hook of one of my pages. The idea is to check if a token is present before ...

In my efforts to reset the TypeORM MySQL database upon server shutdown in NestJS, I am exploring different approaches

I am looking for a way to clear all entries in my database when the server shuts down. Can anyone help with this? export class RoomsService { async onApplicationShutdown() { await this.roomService.deleteAll() } async deleteAll(): Promise<Delete ...

The global CSS styles in Angular are not being applied to other components as expected

Currently utilizing Angular v10, I have a set of CSS styles that are meant to be used across the entire application. To achieve this, I added them to our global styles.css file. However, I'm encountering an issue where the CSS is not being applied to ...

TimeoutException occurs in Browser when using Visual Studio with ASP.NET and Angular

After waiting for 60 seconds, an error message appeared in the browser when trying to debug. However, after refreshing the browser window and waiting for another 15 seconds, everything seemed to be working fine. An unexpected error occurred during the r ...

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Contrasting Compositions with Generics

Let's consider a scenario where we have an abstract class A and three concrete classes that inherit from it: A1, A2, and A3. There is also another hierarchy tree with an abstract class B and three concrete classes B1, B2, and B3. Each concrete class A ...

Angular Reactive Forms - Adding Values Dynamically

I have encountered an issue while working with a reactive form. I am able to append text or files from the form in order to make an http post request successfully. However, I am unsure about how to properly append values like dates, booleans, or arrays. a ...

Troubugging the back-end of Angular Universal Starter App in VS Code is malfunctioning

Currently, I am working on debugging the server-side code for the Angular 2 Universal Starter project on VS Code. The Angular 2 Universal Starter project itself uses VS Code and includes a launch.json file. Despite setting breakpoints in the backend code ...