Angular 16 throwing a NullInjectorError within an interceptor

Currently, I am working on setting up a new interceptor within an Angular 16 project. However, when attempting to inject MatSnackBar into the project, I encounter the following error message:

NullInjectorError: NullInjectorError: No provider for MatSnackBar!

My goal is to display a snackbar notification whenever the API returns an error code. To simplify this process, I created a snackbar service. Unfortunately, both using the service and MatSnackBar directly result in the same error.

Below is a snippet of the interceptor code:

export const requestErrorsInterceptor = (
    req: HttpRequest<unknown>,
    next: HttpHandlerFn
): Observable<HttpEvent<unknown>> => {
    try {
        let matsnack = inject(MatSnackBar);
        //let snackBarService = inject(SnackBarService);
    } catch (error) {
        console.log(error);
    }

    return next(req).pipe(
        map((event: HttpEvent<any>) => {
            return event;
        }),
        catchError((err: any) => {
            if (err instanceof HttpErrorResponse) {
                let message = '';

                if (err.status === 0) {
                    message = 'connection-issues-message';
                }

                return throwError(() => err);
            }
        })
    );
};

Here is my provider setup:

import {
    HTTP_INTERCEPTORS,
    provideHttpClient,
    withInterceptors,
} from '@angular/common/http';
import { EnvironmentProviders, Provider } from '@angular/core';
import { requestErrorsInterceptor } from './interceptors/request-errors.interceptor';
import { requestInterceptor } from './interceptors/request.interceptor';

export const provideApplication = (): Array<Provider | EnvironmentProviders> => {
    return [
        provideHttpClient(
            withInterceptors([requestErrorsInterceptor])
        ),
        {
            provide: HTTP_INTERCEPTORS,
            useValue: () => {},
            multi: true,
        },
    ];
};

Answer №1

Implement a Class-based Interceptor

@Injectable()
export class RequestErrorInterceptor implements HttpInterceptor {
    constructor(private notificationService: NotificationService) {}
    
    intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        // Add your custom interceptor logic here...
    }
}

Then include it in your providers array

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

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

Using Firebase: retrieving getAdditionalUserInfo in onCreate of a Firebase Cloud function

Can anyone help me figure out how to retrieve extra data from a SAML login provider in the backend (firebase functions)? I can see the data on the client side but I'm struggling to access it in the backend. I've specified these dependencies for ...

Locate every instance where two arrays are compared in TypeScript

My goal is to search for matches in Object 2 where the _type corresponds to filterByCallTypeTitulo in Object 1, and then create a new array including all the matched information from Object 2. I attempted to achieve this using the filter() method and forE ...

When an Angular2 application is deployed on a server running NginX, child components fail to load

After deploying my Angular2 app on a server as a Docker image and serving it with NginX, I encountered an unexpected issue. When I ran the webpack-dev-server locally to verify if the build was successful, everything looked fine https://i.sstatic.net/wQQ7 ...

Exploring the versatility of Highcharts with callback functions and comprehensive

Currently, I am utilizing Highcharts with angular 9. Here is the link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk For running on the application side or test side, follow these instructions: Test Side: In the angular.json file at line ...

Issue with ngmodel causing placeholder in Angular 2 md-input to not move up

While working with Angular Material to style an input field, I noticed that the placeholder does not move up when there is a value in the input. This behavior occurs only when using ngModel to bind the input. Interestingly, clicking on the input causes the ...

When running the command `npm audit fix --force`, an error is triggered stating that the data path ".builders['app-shell']" must contain the mandatory property 'class'

After installing a package, I received the following message: added 1 package from 8 contributors and audited 49729 packages in 23.754s found 25 vulnerabilities (1 low, 24 high) run `npm audit fix` to fix them, or `npm audit` for details I proceeded to ...

building an angular feature that displays dynamic checkboxes in rows based on certain conditions

In my Angular application, I am generating dynamic components such as checkboxes, radio buttons, textboxes, etc. based on server configuration. The issue I am facing is with displaying checkboxes in column settings. For example, if there are 6 checkboxes a ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Loading a view in Ionic2 with Angular2 after a successful subscription

After completing an http post request, I want to navigate to the next view in my app. Here is a breakdown of the three services I am using: The server service handles generic http calls such as get and post requests. The city service stores a list of ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

On localhost, Angular 2 route parameters are automatically converted to lowercase, while they stay capitalized on the server

I am currently working on a .NET Angular 2 program that has a route set up like this: <ControllerName>/:id While running it on localhost with IIS Express, the id route parameter automatically gets converted to lowercase in the URL without any addi ...

The chart is failing to refresh with the latest response information (using Chart.js version 3.2.1 and ng2-charts version 3.0.0-beta.9)

I recently upgraded my project using Chart.js version 3.2.1 and ng2-charts version 3.0.0-beta.9. Initially, everything seemed to be working fine with mock data - the charts were displaying as expected. However, when I switched to testing with real backend ...

When an email link is clicked in Angular, Internet Explorer is automatically logged out and needs to be refreshed

I'm currently working on a project using an Angular 4 Application. One of the elements in my HTML code is an href link that has a mailto: email address. The issue I'm facing is that when I click on this link while using IE11, either I get autom ...

"Organize your files with React and TypeScript using a file list

interface IVideos { lastModified: number, name: string, path: string, size: number, type: string, webkitRelativePath: string } const [videos, setVideos] = useState<IVideos[] | null>([]); <input type="file" onChange={(event) => ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

Developing a Progressive Web App with ASP.NET Core 3 and Angular is a powerful

I have embarked on the journey of building an Angular SPA in ASP.NET Core 3. To kick things off, I created a new project, utilized the Angular template, and upgraded all packages to version 8.2.9 of Angular. Setting up a seamless CI/CD pipeline to Azure wa ...

How can I ensure that several components are correctly subscribing to an observable at the same time?

I am working on a client service that has a method: receiveData (params) { return this.http.get(url, { params: params }); } Then there is a service that utilizes this: getData () { return this.client.receiveData(this.params); } Later on, there is a c ...

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

Angular2: dynamic spinner directive for showing progress/loading overlay

Struggling to implement a loading indicator/overlay in Angular2 that can be added to any container div. When the boolean property isLoading changes, I want the div to grey out and display a spinning indicator, then revert back when the property changes. I ...

Are you looking to use the 'any' type instead of the 'Object' type? Angular Services can help you with that

I encountered the following error message: Argument of type 'OperatorFunction<APISearch[], APISearch[]>' is not assignable to >parameter of type 'OperatorFunction<Object, APISearch[]>'. The 'Object' type is ...