在Angular 5中创建Interceptor时,如何让请求正常执行?
在Angular 5中创建拦截器并让请求正常执行的方法
要让拦截器里的请求按正常流程走,核心中的核心就是在intercept方法里调用next.handle(req)并返回这个Observable——这一步相当于把请求传递给HTTP处理链的下一个环节,保证请求能继续发送到服务器、并接收后续的响应。
我结合你给出的代码片段,整理了一个完整的可运行示例,你可以参考:
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse} from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { tap, catchError } from 'rxjs/operators'; import {NgbModal} from '@ng-bootstrap/ng-bootstrap'; import { ErrormodalComponent } from '../../features/errormodal/errormodal.component'; @Injectable() export class CustomHttpInterceptor implements HttpInterceptor { constructor(private modalService: NgbModal) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // 可选:对请求做预处理,比如添加自定义请求头(注意请求对象是不可变的,需要clone后修改) const modifiedReq = req.clone({ headers: req.headers.set('X-App-Custom-Header', 'Angular5-Interceptor-Demo') }); // 关键步骤:调用next.handle()让请求继续执行,同时可通过操作符处理响应或错误 return next.handle(modifiedReq).pipe( tap(event => { // 处理成功响应的逻辑,比如打印日志 if (event instanceof HttpResponse) { console.log(`请求 ${req.url} 成功,响应状态:${event.status}`); } }), catchError((error: HttpErrorResponse) => { // 处理错误的逻辑,比如弹出你定义的错误模态框 this.modalService.open(ErrormodalComponent); // 重新抛出错误,让订阅该请求的组件能捕获到错误信息 return Observable.throw(error); }) ); } }
额外必做步骤:注册拦截器
别忘了在你的根模块(比如AppModule)的providers里注册这个拦截器,否则Angular不会启用它:
import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { CustomHttpInterceptor } from './path-to-your-interceptor'; @NgModule({ // ...其他模块配置(declarations、imports等) providers: [ { provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptor, multi: true // 允许同时存在多个拦截器,按注册顺序执行 } ] }) export class AppModule { }
几个小提醒:
- Angular 5里一定要用
@angular/common/http下的HttpInterceptor,别和旧的Http模块混淆,两者不兼容; - 如果不需要修改请求,直接返回
next.handle(req)就行,克隆请求只是为了遵循请求对象不可变的设计; - 处理错误时记得重新抛出错误,否则订阅请求的地方会收不到错误通知。
内容的提问来源于stack exchange,提问作者Shamoon
相关产品推荐
相关产品推荐

