【问题标题】:RXJS 6: new version of HttpInterceptorRXJS 6:新版本的 HttpInterceptor
【发布时间】:2018-11-01 15:59:54
【问题描述】:

我正在将 rxjs_compat 添加到我的项目中,以便迁移到库的 v6。

但是,用于全局错误处理的现有 HttpInterceptor 不再编译。不知道该去哪里。各种都试过了。尝试的所有内容都出现类型不匹配。

import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
  HttpErrorResponse
} from "@angular/common/http";
import { Observable, of, empty } from "rxjs";
import { ToastrService } from "ngx-toastr";
import { environment } from "../../environments/environment";
import { catchError, map } from "rxjs/operators";

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(private toastr: ToastrService) {}
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError(err => of(HttpErrorResponse)),
      map(err => {
        let message: string;
         this.toastr.error(`${message}`, "Application Error");
        return Observable.empty<HttpEvent<any>>();
      })
    );
  }
}

src/app/shared/http-error-interceptor.ts(26,27):错误 TS2339: “typeof Observable”类型上不存在属性“empty”。

empty 现在是一个常量,但不接受类型,所以这也不起作用。在the upgrade notes 中也找不到太多内容

编辑

虽然有趣的是这样编译:

return Observable.of<HttpEvent<any>>();

【问题讨论】:

  • 尝试return empty(); 有效吗? empty 现在是常量 (EMPTY) 和函数 (empty(scheduler?: SchedulerLike))。
  • 恭喜你的绅士化头像的名字。简森巴顿万岁 \o/
  • 还有孙悟空!!
  • @statosdotcom 尝试过,但intercept 输入安全Observable&lt;HttpEvent&lt;any&gt;&gt;
  • 这个怎么样:return of&lt;HttpEvent&lt;any&gt;&gt;();

标签: angular typescript rxjs angular6 rxjs6


【解决方案1】:
  1. import {EMPTY} from 'rxjs';

  2. 将返回 Observable.empty() 替换为

    return EMPTY;

【讨论】:

    【解决方案2】:

    无法弄清楚如何返回编译器接受的内容,但至少能够抛出错误。代码可以编译运行,但作为 Rxjs 的初学者,不确定是否正确。

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const xhr = req.clone({
          headers: req.headers.set('X-Requested-With', 'XMLHttpRequest')
        });
        return next.handle(xhr).pipe(
          catchError((err) => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 401) {
                this.router.navigate(['/login']);
              } else {
                this.snack.open('Communication error: ' + err.status + ' - ' + err.statusText, null,
                 {duration: 5000, panelClass: 'snack-error', verticalPosition: 'top'});
              }
              return throwError('backend comm error');
            }
          })
        );
      }
    

    【讨论】:

    • 向最终用户提供详细的异常消息很少是一个好的选择
    • @Arthur 如果 err 不是 HttpErrorResponse 的实例,则不会返回 catchError 中的任何内容
    • @CoreyCole 是的,至少在某处记录另一个错误是个好主意。
    • 我认为你必须返回一些东西,这样可观察链才能继续。它说here 总是从catchError 函数返回一个可观察对象
    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 2018-07-16
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多