Angular中tap操作符已弃用,如何修改HTTP拦截器代码?
解决RxJS tap操作符的废弃警告问题
你的Angular HTTP拦截器代码中,tap操作符出现删除线和警告,原因是RxJS已废弃传入单独next/error回调参数的写法,官方要求改用Observer对象作为参数,该旧签名会在V8版本中被彻底移除。
原代码(存在警告)
import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { tap } from 'rxjs/operators'; import { SpinnerService } from '../sharedServices/spinner.service'; @Injectable() export class CustomHttpInterceptor implements HttpInterceptor { constructor(private spinnerService: SpinnerService) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { this.spinnerService.show(); return next.handle(req) .pipe(tap((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { this.spinnerService.hide(); } }, (error) => { this.spinnerService.hide(); })); } }
修改后的代码(消除警告)
import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { tap } from 'rxjs/operators'; import { SpinnerService } from '../sharedServices/spinner.service'; @Injectable() export class CustomHttpInterceptor implements HttpInterceptor { constructor(private spinnerService: SpinnerService) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { this.spinnerService.show(); return next.handle(req) .pipe(tap({ next: (event: HttpEvent<any>) => { if (event instanceof HttpResponse) { this.spinnerService.hide(); } }, error: (error) => { this.spinnerService.hide(); } })); } }
改动说明
把原来传入tap的两个独立回调函数,合并成一个包含next和error属性的Observer对象:
next属性对应原来的第一个回调,处理正常响应事件error属性对应原来的第二个回调,处理错误情况
这样修改完全符合RxJS最新的API规范,既消除了警告,又保留了原有的加载 spinner 显示/隐藏逻辑。
内容的提问来源于stack exchange,提问作者Behnam Faghih
相关产品推荐
相关产品推荐

