类型“未知”不可分配给类型“HttpEvent<any>” - 尝试在 Angular 应用程序中创建 HTTP 拦截器

问题描述 投票:0回答:1

我一直在尝试在我的 Angular 应用程序中创建一个加载微调器。

我在这里找到了一个有趣的教程(https://medium.com/swlh/angular-loading-spinner-using-http-interceptor-63c1bb76517b)。

一切进展顺利,直到最后一步,当我需要实际创建拦截函数时。

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators'
import { LoadingService } from './loading.service';

/**
 * This class is for intercepting http requests. When a request starts, we set the loadingSub property
 * in the LoadingService to true. Once the request completes and we have a response, set the loadingSub
 * property to false. If an error occurs while servicing the request, set the loadingSub property to false.
 * @class {HttpRequestInterceptor}
 */
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {

    /**
     * 
     * @param _loading 
     */
    constructor(
        private _loading: LoadingService
    ) { }

    /**
    * Called at the start of every HTTP request. This function will try to activate the loading spinner
    * @param request 
    * @param next 
    * @returns 
    */
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this._loading.setLoading(true, request.url);
        return next.handle(request)
            .pipe(catchError((err) => {
                this._loading.setLoading(false, request.url);
                return err;
            }))
            .pipe(map<HttpEvent<any>, any>((evt: HttpEvent<any>) => {
                if (evt instanceof HttpResponse) {
                    this._loading.setLoading(false, request.url);
                }
                return evt;
            }));
      }
}

第一根管子没问题。

但是,第二根管道上有一条红色的大下划线。错误提示如下:

“OperatorFunction”类型的参数不可分配给“OperatorFunction”类型的参数。 类型“unknown”不可分配给类型“HttpEvent”。ts(2345)

enter image description here

我在 VSCode(蓝色)和 Microsoft VS(紫色)中看到错误,这意味着我的代码肯定有问题,而不是我的 IDE 很奇怪......

这篇文章写于 2020 年 6 月(4 年前),所以也许 Angular 可观察量的工作方式发生了变化?

我已经学习 Angular 大约 1 周了,对 typescript 也不太熟悉,所以如果我缺少一些基础知识,我很抱歉,但希望得到一些指导,因为我不知道如何继续......

如果 stackoverflow 专家有任何建议,我们将不胜感激。

谢谢!

javascript angular angularjs typescript angular-http-interceptors
1个回答
0
投票

catchError
,必须返回一个可观察的,所以我使用
of
将错误转换为可观察的,这导致了地图下游的错误。

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this._loading.setLoading(true, request.url);
    return next.handle(request).pipe(
      catchError((err) => {
        this._loading.setLoading(false, request.url);
        return of(err);
      }),
      map<HttpEvent<any>, HttpEvent<any>>((evt: HttpEvent<any>) => {
        if (evt instanceof HttpResponse) {
          this._loading.setLoading(false, request.url);
        }
        return evt;
      })
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.