How can I automatically refresh the HTTP service in Angular 6 after encountering an error?

My service is set up to make an http get request that responds with a list of products:

import 'rxjs/Rx';
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class ProductService{
  constructor(private _http:Http) {}

  getData() {

      return this._http.get(`URL GOES HERE`)
        .map(res => res.json());

  }
}

This component uses the service:

import { Component, OnInit }  from '@angular/core';
import { ProductService } from './product.service';
class ProductListComponent implements OnInit {
  constructor(public _productService: ProductService) {}

 ngOnInit() {
    this._productService.getData()
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
}

I am looking for a way to handle errors. If the service encounters an error, I want to refresh it:

this._productService.getData()
      .subscribe(data => this.products = data,
               err => { **recall this._productService.getData()** }

Thank you for all responses

Answer №1

To easily implement retries in your application using RxJS, you can make use of the retry operator from rxjs/operators. Simply specify the number of times you want to retry by adding it as an argument inside the retry(x_times) function.

...
ngOnInit() {
    this._productService.getData().pipe(retry(1))
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
...

Answer №2

Instead of using the retry operator, you can opt for the retryWhen operator to prevent a rapid succession of http calls. This allows you to retry the call specifically in the event of a 503 error (Service Unavailable).

.pipe( retryWhen(error => {
       return error.pipe(
        flatMap((error: any) => {
             if(error.status  === 503) {
               return Observable.of(error.status).delay(1000)
             }
             return Observable.throw({error: ''});
          }),
          take(3) // controls number of retries
      )                
});

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

The element is absent in Type {}, however, it is mandatory in Type '&' and '&' cannot be designated to String Index Type Errors

I have a goal of passing the logged-in user's email address to a 'dict' as a key, fetching its corresponding token value, and using it as a query parameter for an API call. The user's email is retrieved from the user data upon login, sp ...

The property 'value' is not recognized on the Element type

I am currently working on a project where I need to calculate the total sum of values entered in a specific column within a mat-table. The setup involves creating a table with three columns: Account Id, Account Description, and Value. Additionally, I have ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

Material 2's portal host fails to display the specified template portal

Check out the Demo Plunker here: https://plnkr.co/edit/Ye8MAUmrMEQKnPt93TjT?p=preview I'm following the guidance from Material 2 documentation in order to establish a template portal that will be displayed within a nearby host (although my ultimate g ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

Create an array variable for services in Angular

My goal is to define this user as an array. users = new BehaviorSubject<any>([]); In my component, I am attempting to add the userID to the array. this.Service.users.push(userID); To subscribe to it, I use the following code: this.Service.users.su ...

`Incorporating CSS Pseudo-elements to Customize Angular Font Awesome Icons Issue`

I successfully integrated @fortawesome/angular-fontawesome into my Angular 7 application by following the instructions provided on https://www.npmjs.com/package/@fortawesome/angular-fontawesome. Although I am able to use the icons directly, I am facing di ...

Start by incorporating the Reactive Forms Array feature in Angular

Please check out the relevant Plunker by clicking on the link below: https://plnkr.co/edit/f0BxpinhuqVz8o6IIFaL?p=preview Stack Overflow requires code to be included when sharing a Plunker link. However, it's too much code to paste here and would ma ...

Unlinking checkbox click event from row in Angular Material table

I am seeking to remove the ability for row selection in my table rows so that clicking anywhere within the row does not check the checkbox. I want the checkbox to only be checked when the box itself is clicked, allowing me to later add expandable rows when ...

Inversify employs dependency injection similarly to how Angular utilizes TypeScript decorators

Today I made the switch from a js electron project to typescript and found myself wondering about the equivalent of angular's dependency injection. Since Angular Universal is still in its early stages and lacks documentation on using it with electron ...

Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button: import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core'; @Directive({ ...

Guide on utilizing map function and reassigning the value

I am facing a challenge with a list of books that have IsEnable defaulting to False. During onInit(), I need to check each book to see if it is enabled. I was considering using an rxjs map and calling the getEligibleBooks() function within the map, but I ...

Experiencing a useContext error when implementing MDX with NextJS 13

I am currently working on integrating mdx files into Next.js 13. After completing all necessary configurations in next.config and creating the file structure, I have the following path within the app folder: > docs > components > accordion > pa ...

Encountering a NextJS _app.tsx problem - error - Issue with ./pages/_app.tsx file: line 3

Having trouble creating a custom script for my NextJs Project. Here's the error log: Error - ./pages/_app.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'react' 2 | import '../styles/globals.css&apos ...

The directory designated as 'rootDir' should encompass all source files within it

In my Angular CLI workspace, I have two library projects named foo and bar. The issue arises when I try to build the second library, foo, as it fails with the following error: Error TS6059: File '/code/projects/bar/src/lib/types.ts' is not loc ...

Unselected default option in Angular 4's select dropdown

My goal is to use Angular to retrieve a value from a variable and display it as the first option in a select element, while keeping the rest of the options below static. The issue I am facing is that even though Angular is fetching the data successfully, t ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

Generating Typescript definition files from JavaScript files with module.exports assignment

I'm currently working on creating a custom TypeScript definition file for format-duration: module.exports = (ms) => { let { days, hours, minutes, seconds } = parseMs(ms) seconds = addZero(seconds) if (days) return `${days}:${addZero(hours)}: ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Top method for dynamically generating a recursive treeview from data fetched from an API

I am currently learning Angular 2 and working on creating an expandable tree-view that pulls data from a potentially large third-party API. The underlying structure of the API is structured like this: - Home (id: 1053) - - Rugby League (id: 1054) - - - Su ...