The error message "Type 'unknown' cannot be assigned to type 'HttpEvent<any>'" is appearing while attempting to create an HTTP interceptor within an Angular application

Attempting to implement a loading spinner in my Angular application has been quite the journey.

Stumbled upon an intriguing tutorial at this link (https://medium.com/swlh/angular-loading-spinner-using-http-interceptor-63c1bb76517b).

Everything was going smoothly until I hit the final step, where creating the intercept function became necessary.

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators'
import { LoadingService } from './loading.service';

/**
 * Class designed to intercept http requests. Initializes loadingSub property in LoadingService as true on request start. Once request is completed and response received, sets loadingSub to false. In case of error during request handling, also sets loadingSub to false.
 * @class {HttpRequestInterceptor}
 */
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {

    /**
     * 
     * @param _loading 
     */
    constructor(
        private _loading: LoadingService
    ) { }

    /**
    * Called at the beginning of every HTTP request. Activates loading spinner at start.
    * @param request
    * @param next
    * @returns 
    */
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this._loading.setLoading(true, request.url);
        return next.handle(request)
            .pipe(catchError((err) => {
                this._loading.setLoading(false, request.url);
                return err;
            }))
            .pipe(map<HttpEvent<any>, any>((evt: HttpEvent<any>) => {
                if (evt instanceof HttpResponse) {
                    this._loading.setLoading(false, request.url);
                }
                return evt;
            }));
      }
}

The first pipe seems fine.

But now, there's a glaring red underline indicating an issue with the second pipe. The error message reads:

Argument of type 'OperatorFunction<HttpEvent, any>' is not assignable to parameter of type 'OperatorFunction<unknown, any>'. Type 'unknown' is not assignable to type 'HttpEvent'.ts(2345)

https://i.sstatic.net/Jp7LNqi2.png

In both VSCode (blue underline) and Microsoft VS (purple underline), the error persists, implying it's a coding issue rather than just a quirk of the IDE...

This article dates back to June 2020 (4 years ago), leading me to think that there may have been changes in how Angular observables operate?

I've only been diving into Angular for a week, and TypeScript is still somewhat foreign to me, so please excuse any oversights on my part. Any guidance would be greatly appreciated, as I'm unsure about the next steps...

If any Stack Overflow experts have insights, they'd be immensely valuable.

Thank you!

Answer №1

To handle errors in the intercept function, I make sure to return an observable by using of to convert the error into an observable. However, this approach is leading to issues downstream on the map operation.

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this._loading.setLoading(true, request.url);
    return next.handle(request).pipe(
      catchError((err) => {
        this._loading.setLoading(false, request.url);
        return of(err);
      }),
      map<HttpEvent<any>, HttpEvent<any>>((evt: HttpEvent<any>) => {
        if (evt instanceof HttpResponse) {
          this._loading.setLoading(false, request.url);
        }
        return evt;
      })
    );
  }

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

How to stop a loop of method calls that return a Promise<any> in TypeScript

My current issue involves a loop in which a method is called, and the method returns an object of type Promise<any>. I need to break the loop if the response from the method is correct. However, using the break statement does not stop the loop as exp ...

Utilizing String.Format in TypeScript similar to C# syntax

Is there a way to achieve similar functionality to String.Format in C# using TypeScript? I'm thinking of creating a string like this: url = "path/{0}/{1}/data.xml" where I can substitute {0} and {1} based on the logic. While I can manually replace ...

The visibility of a ThreeJS mesh disappears when its center moves out of the camera's view

Struggling to develop a map featuring various meshes, I've encountered an issue where meshes disappear when the center of the mesh is out of the camera view. Check out this gif demonstrating the problem: Currently using THREE.WebGLRenderer 71, is th ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

Secure Authentication with AngularJS and Java Server Pages

I have recently built an angular js - jsp application and I've set up a login page along with a servlet to fetch data from the database for comparison of username and password. Now, my challenge is passing information to the servlet for authentication ...

How about adjusting this RPG Battle Sequence?

Both the client and server sides of my game are built in JavaScript. I have opted not to implement a master game loop since combat is infrequent and nothing else in the game requires one. When two players engage in combat, they enter an auto-attack loop as ...

Is it feasible to remain on the page and receive a confirmation message once the file has been successfully uploaded

After uploading and clicking Submit, the page changes without using the JavaScript below. The JavaScript is meant to ensure that the page remains unchanged. Issue While the HTML and JavaScript keep the page as desired and retrieve the radio button value, ...

Deactivate the rest of the buttons by utilizing the e.target.id

I have ten expansion panels. When I click a button in one expansion panel, I want to disable other buttons in the remaining expansion panels. The issue is that when I try to target an id, it does not return e.target.id but instead returns as the value pass ...

Access to the server has been restricted due to CORS policy blocking: No 'Access-Control-Allow-Origin'

I’m currently encountering an issue with displaying API content in Angular and I’m at a loss on how to troubleshoot it and move forward. At this moment, my main objective is to simply view the URL data on my interface. Does anyone have any insights or ...

Adding a transition effect to a div in CSS when switching from col-12 to col-9

I am facing an issue with the CSS provided below. It seems to only work when I close my div with the class "onclick-div". However, the transition effect is not visible when I click on the button to reduce the width of the div with the class "set-transiti ...

Protected knockout observable

Incorporating the protected observable into my code has been a goal of mine, so I stumbled upon this helpful tutorial: HERE While experimenting with the demo on the website, I encountered an interesting scenario: Initially, click the edit button for a ...

When attempting to invoke a JavaScript function on JSP, there seems to be no

I am currently developing a web application and delving into the intricacies of how Ajax functions within it. I am encountering an issue where nothing occurs when I attempt to select a category, and no errors are being reported. Within my JSP page: < ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

Use the row().data function with the datatables.net plug-in to fetch data from a specific column in a

UPDATE: Removed my video on YouTube, but here is a straightforward solution: $(document).on('click', '.edit_btn', function() { var rowData = $('#example').DataTable().row($(this).parents('tr')).data(); }); "Funct ...

Utilizing Vue for Efficient Search Box and Checkbox Filtering System

I am currently working on developing a filter system using Vue. Update The filters are functioning properly, but all the computed functions are separate. Is there a way to combine them into one function for better efficiency? export default { da ...

Problem encountered when attempting to use 'delete' as a property name

I am currently encountering an issue with a form that deletes a gallery from a database. Previously, the code was functioning properly but after some recent updates such as switching from jquery.interface to jquery-ui, I am now facing difficulties. Wheneve ...

Tips on leveraging LocalStorage to update state in ReactJS

In my code, an array fetches API data each time componentDidMount() is called. Within this array, each element contains an object with a default boolean value of true. An onClick function toggles the boolean value of a specific element to false when clicke ...

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

Tips for efficiently inserting large amounts of JSON data using node.js

My goal is to insert this JSON data into my SQL Server database. The JSON consists of bulk data with a detailed structure. Below is an example of the JSON data I aim to insert: [ { No_BPS:'BSWEB12345', Kd_Plg:'MMIM026', ...

Angular ng-repeat with toggle filter

Looking for a way to display data in an angular application using ng-repeat? Want to add and remove filters on the displayed data with a simple click? You're in luck. Implementing a toggle filter functionality is easier than you think. If you've ...