I am having an issue with the HttpInterceptor in my Angular7 application not functioning properly when errors occur. Can anyone help me troubleshoot the

I'm working on implementing multiple interceptors in my Angular7 project for tasks like authentication and error handling. However, I feel like I might be overlooking something simple and would appreciate a fresh set of eyes to help me spot any mistakes.

One key thing I know I need is the new HttpClientModule for Angular7.

In my app.module.ts file:


import { HttpClientModule } from '@angular/common/http';

imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
],

providers: [
    AuthService,
    ErrorInterceptor
],

Here is my errorInterceptor.ts code:


import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {

            const error = err.error.message || err.statusText;
            return throwError('Oops! An error occurred:', error);
        }));
    }
}

And here is my my.service.ts code:


import { Injectable } from '@angular/core';
import { map} from 'rxjs/operators';
import { HttpClient } from "@angular/common/http";

@Injectable({
    providedIn: 'root'
})
export class MyService {

    constructor(private http: HttpClient) {
    }

    getSomeData() {
        this.http.post<any>(`https://getsomedata.com/youneedthisdata`, {})
            .pipe(map(response => {
                console.log('Testing service', response);
            })).subscribe();
    }
}

If you require more code or information, please let me know. Any assistance will be greatly appreciated!

Answer №1

The problem lies in the requirement for specific syntax to set up the interceptor.

{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }

This code snippet should be included within your providers array instead of the current configuration for ErrorInterceptor.

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 extract a value from [object object] in Angular4

In my previous question, I shared the code below: getUserRole() { const headers = new Headers(); headers.append('Authorization', `Bearer ${this.getToken()}`); console.log(this.getToken()); const options = new RequestOptions({ headers: he ...

What is the proper way to eliminate the port from a URL so that the images sourced from the XAMPP database can function correctly?

I am a beginner in Angular and I am facing an issue with Angular and XAMPP. I am attempting to load images from mySQL database where I stored their destinations. The problem is that Angular is trying to access that destination through this link: https://i ...

Using class variance authority variants allows for the acceptance of a "null" value, although it is not recommended

My approach with cva is as follows: const checkboxOptions = cva('border ...', { variants: { size: { sm: 'h-4 w-4', md: 'h-5 w-5', lg: 'h-6 w-6', }, }, defaultVariants: ...

"Updating the value of a select option in real-time

As a beginner in angular 6, I am working on populating a select field using reactive forms. <form [formGroup]="form"> <select id="estimated-volume" [formControlName]="'usage'"> <option [value]="null">Usage</optio ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

Guide on setting up a chart using data fetched from an API?

I'm looking to incorporate ngx-charts into my project, but I'm struggling with initializing the chart with data retrieved from my API. Setting up a vertical bar chart seems straightforward. The data structure I have is like this: https://stackb ...

Is there a way to create an interpolated string using a negative lookahead condition?

When analyzing my code for imports, I will specifically be searching for imports that do not end with -v3. Here are some examples: @ui/components <- this will match @ui/components/forms/field <- this will match @ui/components-v3 ...

When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the ro ...

Nx workspace combined with the use of localstorage for data storage

Currently, I am working on a project that involves utilizing Nrwl Nx workspace to maintain a unified codebase across various applications (web, ionic 4, electron). I am seeking advice on the best approach to incorporate local storage functionality in ...

Angular 2 is showing an error message: TS1005 - It is expecting a comma

Upon compiling, I encountered the following error: I am unable to locate where a comma needs to be inserted. src/app/navbar.component.ts(29,39): error TS1005: ',' expected. src/app/tache.service.ts(53,53): error TS1005: ',' expected. ...

Creating CSS from Angular stylesheets?

Are there any methods available to view the CSS corresponding to SCSS when using SCSS as the preprocessor for Angular? You can find a solution here: When using angular with scss, how can I see the translated css? The answer suggests using the --extract-c ...

Creating interactive forms with Angular 9 using ngx-formly and arrays for dynamic form generation

Looking to implement: Dynamic Forms based on user-selected locale JSON using ngx-formly/material. How can I connect fields with my array of objects "this.fields2"? In my component.ts file, I have: model: any = {}; options: FormlyFormOptions = {}; fields: ...

Expectation in Observable: Unable to provide data retrieval

In my Angular 7 and Typescript project, I am faced with the challenge of reading a json file from within a zip file. Although I am able to successfully display the correct json output on the console, I am struggling to return this json data from the functi ...

Exporting External JavaScript Variables in Angular 2 Using Typescript

In my Configuration JS file, I have defined some configuration variables. For example: var config = {url:"xyz.com"}; I need to access these configuration parameters throughout my application. I attempted to export the config variables like this: export ...

What is the rationale behind declaring variable System as any?

The repository for Angular material can be found on GitHub at https://github.com/angular/material.angular.io. Within the source code, there is a typings.d.ts file that contains a type definition: declare var System: any; I am curious about the purpose of ...

In Angular2+, is it possible to reset a radio button when the reset button is clicked?

Here is the HTML code that I use: <div class="dropdown-menu dropdown-menu-right filter-dropdown-menu row"> <input type="radio" class="filter-dropdown-menu-padding" (click)="filter_source_type(0)" name="gender" value="male"> Admin & ...

By using providedIn: 'root', services are automatically registered for testing

It could be due to the new functionality, but when I have a service like this: @Injectable({ providedIn: 'root' }) export class MyService {...} and my MyComponent uses it. When testing that component, I simply do this and it works! TestBed.c ...

Adaptable transformations within ngx-bootstrap carousel

Currently, I am in the process of learning Angular and I have encountered a problem while trying to make my site responsive using ngx-bootstrap carousel. Is it achievable to implement responsive changes within the ngx-bootstrap carousel? In the main v ...

If the children prop is used to pass a server component to a client component, will it be displayed/rendered on the client side?

The documentation for NextJS explains in this section that all child components and modules imported into a client component are considered part of the client bundle. However, it also mentions the option to mix server and client components by passing a ser ...

Preventing Page Refresh when Button is Clicked in Angular

How can I prevent page reload when a button is clicked in Angular? I'm developing a quiz application in Angular where I fetch random questions and options from an API. When users select an option, the next question should appear without reloading the ...