在Angular 8中,可以在拦截器中订阅可观察对象,可以按照以下解决方案进行操作:
HttpInterceptor
接口:import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
// 处理响应数据
}
})
);
}
}
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { CustomInterceptor } from './custom-interceptor';
@NgModule({
imports: [HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
}
]
})
export class AppModule { }
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const modifiedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer your-token') });
return next.handle(modifiedReq).pipe(
tap(event => {
if (event instanceof HttpResponse) {
event.body = this.modifyResponseData(event.body);
}
})
);
}
private modifyResponseData(data: any): any {
// 修改响应数据
return data;
}
}
在这个示例中,我们修改了请求的头部,添加了一个授权令牌,并在收到响应后修改了响应数据。你可以根据自己的需求进行适当的修改。