Is it possible to return an empty array within an HttpInterceptor when encountering an error?

When encountering errors that require displaying empty "lists" in dropdowns, I utilize this interceptor:

public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError((err) => {
  // Check for invalid password returning 401
  if (err.status === 401 && !this.router.url.includes('/auth')) {
    // Automatically logout if 401 response is returned from the api
    localStorage.removeItem('token');
    location.reload();
  }
  // Error alert
  if (this.router.url.includes('/auth')) {
    this.message.error(
        err.error ?? err.statusText,
        { nzDuration: 5000,
          nzPauseOnHover: true },
    );
  }
  console.log(err);
  // Return an empty array here
  return throwError(err);
}));
}

By using catchError in all my getSomethingMethod(), can I achieve the same outcome through interceptors?

The example provided in the comments does not work: https://stackblitz.com/edit/angular-ivy-rhtclm?file=src/app/error.ts does not trigger the "res" section.

Answer №1

return next.handle(request).pipe(catchError((err) => {
    console.log(err);

    // this section would result in an error
    // return throwError(() => err.message);

    // this section will complete without any resolution
    // return EMPTY

    // This section will resolve with an empty array in the next step
    return of(new HttpResponse({ body: [] }));
  }));
}

NOTE:

Why did I use HttpResponse within of()?

The reason is that in order to proceed with the call, you must return an observable containing HttpResponse values in the interceptor. Other types of values will be disregarded.

Answer №2

Absolutely, it is possible. Feel free to display any errors to the user within a message or dialogue box in this portion of code and make sure to return EMPTY at the conclusion.

import { EMPTY } from 'rxjs';

catchError((error: HttpErrorResponse) => {
     
        if (error) {
          showMessage('messages.tryAgain');
        } 

        return EMPTY
})

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

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

AngularJs does not properly update the scope of a scoped directive when using ng-repeat within itself

The issue arises from calling Directive1 within the same Directive1 using ng-repeat. Although directive11 has a value in scope, when calling the nested directive with a new value, it appears to retain the initial value. I attempted to invoke the same dire ...

Can a video be embedded within a popover element?

My goal is to insert a short video into my popover. I attempted the following method: let htmlString = ` <div class="embed-responsive embed-responsive-16by9"> <video class="embed-responsive-item" src="..." loop muted></video&g ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

Transitioning effect when tapping a link that guides you to a different section of the webpage

Just by reading the title, you can understand my concern. Currently, when I click on "Example 4", the page abruptly scrolls to the h1 of Example 4. It looks so ungraceful, like a sudden boom. I would prefer a smooth scrolling effect. Is it possible to achi ...

Guide on passing a JSON body as a string in a PUT API request using Fetch in a React.js application

How can I pass a JSON body as a string in a FETCH PUT API in React JS? I am attempting to add 20 to the Balance like this: Balance: details[0].Balance.toString() + 20, but it is not working as expected. I want the entire result to be a string. Any assista ...

What is the best way to retrieve the file path of a imported Angular module?

I am trying to figure out how to retrieve the path of the BarComponent within the code snippet below. Specifically, I need to obtain '../bar/bar.component'. When dealing with a module loaded from a package such as Component module, I would like t ...

Tips for preventing multiple clicks when posting AJAX requests in jQuery

Using Django, I was able to create a website and implement a voting page with jQuery AJAX. The code works perfectly fine as shown below: <!doctype html> <html> <head> <script src="jquery-1.10.2.min.js"></script> <met ...

Sending Objects Array in POSTMAN using Hapijs: A Step-by-Step Guide

Could you please assist me on how to send a POST request in POSTMAN for the given array of objects and then validate it using Joi in a hapi server? var payload = [{ name: 'TEST Name 1', answer: 'TEST Answer 1', category: &a ...

All You Need to Know About Jquery's Selector for Nested Elements

Could someone clarify if the Jquery Statement $(selecterA:not(selectorB), elementA) means "return those elements that match selectorA but not selectorB within elementA"? I am confused by a simple case in Fiddle#1, where both output statements using .length ...

Why is there a mismatch between CSS and Angular 6 selector components?

website.html <website-chat></website-chat> chat-page.html <h1>Greetings</h1> chat-script.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'website-chat', templateUrl: '. ...

How to eliminate the validation icon from a select tag in Bootstrap 5?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c57505751425363160d110d11" ...

HTML/Angular tutorial: Sharing an On-Click value with a different HTML element within the same component

As a newcomer to this, I could really use some guidance. Currently, I have a Mat Table that is displaying a specific range of data from my firestore. My goal is to be able to click on a particular row and have its data appear in a list below the table. I ...

How to Create a Speech Bubble in SVG Using SnapSVG

In the process of developing a chat program, I have animated figures moving across the screen engaging in conversations. One crucial aspect I am yet to implement is creating scalable speech bubbles for when users interact. Being relatively new to SVG and ...

Importing GeoJSON data into Meteor's Leaflet

Recently diving into Meteor, I am on a mission to create my own customized version of this impressive example from leaflet incorporated into Meteor: Interactive Choropleth Map The implementation requires the use of this GeoJson Data file: us-states The o ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

What is the best way to sort the values of an associative array in JavaScript?

Consider the following associative array: array["sub2"] = 1; array["sub0"] = -1; array["sub1"] = 0; array["sub3"] = 1; array["sub4"] = 0; How can you efficiently sort this array in descending order based o ...

One way to create a unique JavaScript Module Pattern that retrieves the default value of a

I'm struggling to retrieve the latest private property from a Module, as I keep getting the initial value instead of the most recent one. Upon submission of the form and triggering onSuccess, I assign partnerId = 10. Subsequently, upon clicking an e ...

Tips for maintaining space beneath an image when text wraps around it

.blogimgarea { width: 38%; padding-right: 26px; float:left; } img{max-width:100%} .blogtextarea { width:55%; padding:22px 32px 0 0; float:right; } <div class="newpostregion pt70"> <div class="blogimgarea"> <img class="featblogimg" src="https ...