RXJS 6:新版本的 HttpInterceptor

RXJS 6: new version of HttpInterceptor

我正在将 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): error TS2339: Property 'empty' does not exist on type 'typeof Observable'.

empty 现在是常量,但不接受类型,因此也不起作用。在 the upgrade notes

中也找不到太多

编辑

虽然有趣的是这个编译:

return Observable.of<HttpEvent<any>>();
  1. import {EMPTY} from 'rxjs';

  2. 将returnObservable.empty()替换为

    return EMPTY;

无法弄清楚如何 return 编译器接受的东西,但至少能够抛出错误。代码可以编译并运行,但是作为 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');
        }
      })
    );
  }