Unable to locate 'http' in error handling service for Angular 6

My current project involves creating an Error Handling Service for an Angular 6 Application using the HTTP Interceptor. The main goal of this service is to capture any HTTP errors and provide corresponding error codes. However, my lack of familiarity with Observables, Subscriptions, and the HTTPInterceptor in Angular is causing me some trouble. When I try to compile the following code, I encounter the error message:

error TS2663: Cannot find name 'http'. Did you mean the instance member 'this.http'?
.

Below is the code snippet for the Error Handler:

import { ErrorHandler, Injectable } from '@angular/core';
import { HttpInterceptor, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { InterceptService } from './InterceptService';
import { Http, Headers, RequestOptions } from '@angular/http';

@Injectable()
export class ErrorsHandler extends ErrorHandler {
  private data: any;
  private error: any;

  constructor(
    public http: InterceptService
  ) {
    super();
  }

  handleError(error: Error | HttpErrorResponse) {
    if (error instanceof HttpErrorResponse) {
      // Server or connection error happened
      if (!navigator.onLine) {
        console.log('A mild error has occurred, please check your internet connection!');
      }
      else {
        // TODO: Set Config for Services
        http
          .get('Put Service URL here')
          .map(res => {
            // If request fails, throw an Error that will be caught
            if (res.status < 200 || res.status >= 300) {
              throw new Error('This request has failed ' + res.status);
            } else {
              return res.json();
            }
          })
          .subscribe(
            (data) => this.data = data,
            299(err) => this.error = err);
        }
      } else {
        // Check the Connectivity of Services
        console.log('Please debug the following error', console.error);
      }
      // Log the error anyway
      console.error('Please debug the following error: ', console.error);
    }
  }

And here is the code for the Intercept Service:

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

@Injectable()
export class InterceptService implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest < any > , next: HttpHandler):
    Observable < HttpEvent < any >> {

      // modify request
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${localStorage.getItem('MY_TOKEN')}`
        }
      });

      console.log("----request----");
      console.log(request);
      console.log("--- end of request---");

      return next.handle(request)
        .pipe(
          tap(event => {
            if (event instanceof HttpResponse) {
              console.log(" all looks good");
              console.log(event.status);
            }
          }, error => {
            console.log("----response----");
            console.error("status code:");
            console.error(error.status);
            console.error(error.message);
            console.log("--- end of response---");
          })
        );
    }
}

I am seeking guidance on whether I am using the HTTP Interceptor correctly and how to properly inject it into the Error Handler. Additionally, I need help resolving the error mentioned earlier. Any assistance or tips would be greatly appreciated!

Answer №1

The issue is clear from the error message. The correct syntax in your code should be this.http.

import { ErrorHandler, Injectable } from '@angular/core';
import { HttpInterceptor, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { InterceptService } from './InterceptService';
import { Http, Headers, RequestOptions } from '@angular/http';


@Injectable()

export class ErrorsHandler extends ErrorHandler {
  private data: any;
  private error: any;

  constructor(public http: InterceptService) { super(); }

  handleError = (error: Error | HttpErrorResponse) => {
    if (error instanceof HttpErrorResponse) {
      if (!navigator.onLine) {
        console.log('Some Error!');
        }
        else {
          this.http
            .get('Put Service URL here')
            .map(res => {
              if (res.status < 200 || res.status >= 300) {
                throw new Error('This request has failed ' + res.status);
              } else {
                return res.json();
              }
            })
            .subscribe(
              (data) => this.data = data,
              (err) => this.error = err); // Reach here if fails
        }
      } else {
        console.log('Bitte den folgenden Fehler debuggen', console.error);
      }
      console.error('bitte den folgenden Fehler debuggen: ', console.error);
    }
  }

Answer №2

To include the HttpErrorResponse module in your project, you can use the following lines of code: import { HttpClient, HttpErrorResponse } from '@angular/common/http'; Alternatively, you can also import just the HttpErrorResponse module using: import { HttpErrorResponse } from '@angular/common/http';

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

What is the best way to implement an IF THEN ELSE statement using ngStyle in Angular?

How can I make rows in a table highlight based on the STATUS value? Currently, I have it set up to show yellow if the STATUS is 1 using the following code: [ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : '&a ...

Send out data every 250 milliseconds in a way that resembles debounceTime(), but without any waiting period

When the window is resized, I have a complex operation that rearranges multiple DOM elements. To prevent frequent updates, I implemented debounceTime(250ms) to introduce a delay before refreshing the components. However, this approach can cause issues if ...

Error in Express Session: Property 'signin' is not found in type 'Session & Partial<SessionData>'. Code: 2339

I received the following Error Code: Property 'signin' does not exist on type 'Session & Partial<SessionData>'. (2339) About My Application src/index.ts import "reflect-metadata"; import express = require("expr ...

Uploading files in Angular application

I'm facing some minor issues with file uploads for the first time. My project consists of an Angular 7 app and a NodeJS (express) backend. I have successfully uploaded images through the Angular page and stored them with the correct format in NodeJS. ...

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

Angular4 Leaflet Map encountering errors

Here is the template: <div id="mapid" style="height: 500px"></div> After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import. This is the cont ...

The provider named toasterProvider is not recognized within the dependency injection chain, which includes toaster, RugHttpInterceptor, $http, and ng1UIRouter

Working with Interceptors to show a toast message when my app encounters an HTTP error in responseError code. Using AngularJS Interceptor for an MEAN.JS app. Interceptor Code angular.module('rugCoPro') .factory('RugHttpInterceptor', ...

Call a function within a stateless component in a React application

I have a question regarding my React component. I am attempting to call the function ButtonAppBar within my stateless component, but the TypeScript compiler is throwing an error stating '{' expected. I'm unsure whether I need to pass it to m ...

Encountering issues when implementing any ng statement

Just recently, I completed the installation of node and npm on my Ubuntu system. Along with that, I also installed Angular CLI. However, upon trying to use the ng statement such as ng new test-project, I encountered the following error: ----Mg: -- watch ...

How can you type a collection of initialized class instances in Typescript when given an object containing classes?

Imagine having an object that resembles the following: const typeMap = {category1: Category1, category2: Category2} In this case, Category1 and Category2 refer to classes, and there could potentially be hundreds of different categories. Now I also have a ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

Dealing with situations where an Angular component's route lacks a resolver

I have a component that handles both creating new items and updating existing ones. I have set up a Resolver for the 'edit/:id' route, but have not used one for the 'new' route. ngOnInit() { if (!(this.route.snapshot.url[0].path ...

Common Mistakes when Using Angular 4 Dropdowns

I attempted to implement the Angular 4 Drop Down feature: https://www.npmjs.com/package/ng4-material-dropdown Below is the code snippet for my div element setup: <ng4-dropdown> <ng4-dropdown-menu> <ng4-menu-item *ngFor="let item of ...

Return the previous value if the filter function returns false in RxJs

In an attempt to optimize performance and reduce unnecessary requests to the server, this code checks if values exist in the store before making additional requests. While the overall logic functions correctly, there is an issue where if the filter returns ...

Resolving Node.js Troubles: An Encounter with 'Module Not Found' Error

After generating a new application, I encountered an error while using the "ionic serve" command. [ng] The specified path cannot be found. [ng] internal/modules/cjs/loader.js:883 [ng] throw err; [ng] ^ [ng] Error: 'C:\Users\shane\Co ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

What are the ways in which I can utilize the private or public keyword in TypeScript?

Having issues specifying private or public properties in my TypeScript files (tsx/ts files) for a React project. The IDE being used is WebStorm 2021.3. TypeScript version in use is 4.5.4. Attempts were made to adjust some properties in the tsconfig.json ...

Trouble retrieving query parameters from a URL while trying to access URL parameters from a module

I am currently learning angular and facing a small problem that I'm unsure how to solve. My module looks like this: const hostHandler = setContext((operation: any, context: any) => ({ headers: { ...context?.headers, 'X-Location-Hostn ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Issue encountered with passport-local in TypeScript: Unable to utilize 'new' with an expression that does not have a call or construct signature

Currently, I am attempting to implement the passport-local package in TypeScript (version 2.0.0RC); however, a compiler error has arisen: Error TS2351: It is not possible to use 'new' with an expression lacking a call or construct signature. ...