【问题标题】:Angular 7 : Property 'do' does not exist on type 'Observable<HttpEvent<any>>'Angular 7:“Observable<HttpEvent<any>>”类型上不存在属性“do”
【发布时间】:2018-12-19 10:52:17
【问题描述】:

我创建了新的拦截器名称HttpInterceptor。 下面是示例代码:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse,
} from '@angular/common/http';

import { Observable } from 'rxjs';

import { ErrorHandler } from './error_handler';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {

  constructor(
    public errorHandler: ErrorHandler,
  ) { }

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

    return next.handle(request).do((event: HttpEvent<any>) => { }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        this.errorHandler.handleError(err);
      }
    });
  }
}

我在 app.module.ts 中添加了提供程序

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true,
    }
  ]

我收到了这个错误。

错误:StaticInjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> ErrorHandler]:StaticInjectorError(平台:核心)[InjectionToken HTTP_INTERCEPTORS -> ErrorHandler]: NullInjectorError: ErrorHandler 没有提供者!

我在 Angular 7 中的代码。请帮助我。

【问题讨论】:

标签: angular rxjs angular7


【解决方案1】:

在根目录中添加ErrorHandler,如果不添加提供者,您将无法直接使用任何服务,因此在 Angular 6+ 版本之后,它们引入了新语法,您可以在模块的根目录中添加。

因此您可以在整个应用程序中使用该服务。

例如,

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

在模块的根目录中添加RequestInterceptor

@Injectable({
        providedIn: 'root'
})
export class RequestInterceptor implements HttpInterceptor{
}

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2018-11-16
    • 2018-11-18
    • 2023-04-10
    • 2018-09-19
    • 1970-01-01
    • 2021-09-23
    • 2018-04-19
    • 1970-01-01
    相关资源
    最近更新 更多