12

我正在添加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现在是一个常量,但不接受类型,所以这也不起作用。在升级说明中也找不到太多

编辑

虽然有趣的是这编译:

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

2 回答 2

27
  1. import {EMPTY} from 'rxjs';

  2. 将 return 替换Observable.empty()

    return EMPTY;

于 2018-05-22T20:12:27.507 回答
1

无法弄清楚如何返回编译器接受的内容,但至少能够抛出错误。该代码可以编译并且可以工作,但是作为 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');
        }
      })
    );
  }
于 2018-05-30T10:46:03.753 回答