Angular 6错误处理程序服务中的“找不到HTTP”

时间:2018-08-28 15:33:30

标签: angular typescript angular-http-interceptors

我正在尝试基于HTTP拦截器为Angular 6应用程序构建错误处理服务。错误服务最好应捕获任何HTTP错误并参考相应的错误代码。但是,由于我对Observables,Subscription和Angular的HTTPInterceptor不太了解,因此以下代码为我提供了错误:error TS2663: Cannot find name 'http'. Did you mean the instance member '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) {
      // Server or connection error happened
      if (!navigator.onLine) {
        console.log('Ein leichter Fehler ist vorgefallen, bitte überprüfen Sie 
          Ihre Internetverbindung!');
        }
        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, // Reach here if res.status >= 200 && <= 
              299(err) => this.error = err); // Reach here if fails
        }
      } else {
        // Check the Connectivity of Services
        console.log('Bitte den folgenden Fehler debuggen', console.error);
      }
      // Log the error anyway
      console.error('bitte den folgenden Fehler debuggen: ', console.error);
    }
  }

这是拦截服务:

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() //{providedIn: 'root'}
export class InterceptService implements HttpInterceptor {

  constructor() {}

  // intercept request and add token
  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");
              // http response status code
              console.log(event.status);
            }
          }, error => {
            // http response status code
            console.log("----response----");
            console.error("status code:");
            console.error(error.status);
            console.error(error.message);
            console.log("--- end of response---");
          })
        );
    }
}

我不确定我是否以正确的方式使用HTTP拦截器,以及如何将其正确注入错误处理程序,而且我不知道如何解决该错误;任何帮助或提示将不胜感激!

1 个答案:

答案 0 :(得分:1)

错误说明了一切。它应该在您的代码中为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);
    }
  }