【问题标题】:Type '{}' is not assignable to type 'HttpEvent<any>'类型“{}”不可分配给类型“HttpEvent<any>”
【发布时间】:2020-08-24 13:48:46
【问题描述】:

我有一个错误,我找不到如何解决它,我有一个拦截器,它在令牌过期时获取状态,然后我继续刷新令牌问题是当我提出 Angular 项目时它表明控制台报错,在(return nex .handle(this.addToken(req)).pipe)那一行报错如下。

提前感谢您的帮助。

ERROR in src/app/auth-interceptor.ts(83,19): error TS2322: Type 'Observable<{} | HttpProgressEvent | HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | 
Http...' is not assignable to type 'Observable<HttpEvent<any>>'.
Type '{} | HttpProgressEvent | HttpSentEvent | HttpHeaderResponse | HttpResponse<any> | HttpUserEvent<a...' is not assignable to type 'HttpEvent<any>'.     
Type '{}' is not assignable to type 'HttpEvent<any>'.
Type '{}' is not assignable to type 'HttpUserEvent<any>'.
        Property 'type' is missing in type '{}'.
return next.handle(this.addToken(req)).pipe(
                    catchError((error: HttpEvent<any>) => {
                        if (error instanceof HttpErrorResponse) {
                          console.log("error ",error);
                            switch ((<HttpErrorResponse>error).status) {
                              case 400:
                                return this.handle400Error(error);
                              case 403:
                                  return this.handle403Error(req, next); 
                              default:
                                  return throwError(error);
                            }
                        } else {
                            return throwError(error);
                        }
                    }));

【问题讨论】:

  • 您能否提供拦截器代码以及问题?

标签: angular typescript refresh-token


【解决方案1】:

看来问题出在handle400Errorhandle403Error 方法的返回类型上。 根据catchError docs:

通过返回新的 observable 或抛出错误来捕获要处理的 observable 上的错误。

@return {Observable} 一个 observable,它来自源或 catch selector 函数返回的 observable。

这意味着,catchError 的结果应该是一个错误,或者HttpEvent&lt;any&gt;(源类型)可观察到。

例如以下代码 sn -p 没有类型错误:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: Error) => {
        if (error instanceof HttpErrorResponse) {
          switch ((<HttpErrorResponse>error).status) {
            case 400:
              return this.handle400Error(error);
            default:
              return throwError(error);
          }
        } else {
          return throwError(error);
        }
      }));
  }

  handle400Error(error: HttpErrorResponse) {
    return of(new HttpResponse());
  }

注意:HttpEvent&lt;any&gt; 类型与HttpErrorResponse 类型无关,所以Error 中的错误最好有Error 类型。

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 2018-04-19
    • 1970-01-01
    • 2021-02-06
    • 2023-04-10
    • 1970-01-01
    • 2021-05-21
    • 2019-01-12
    • 2019-06-02
    相关资源
    最近更新 更多