gpt4 book ai didi

angular - 有什么方法可以改变 Angular 5 HttpInterceptor 中的响应吗?

转载 作者:太空狗 更新时间:2023-10-29 18:03:37 25 4
gpt4 key购买 nike

对于我的应用程序,我创建了以下 HttpInterceptor。有没有办法从这里向请求订阅者返回响应的更改版本?

import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(
private router: Router
) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// any way to alter response that gets sent to the request subscriber?
}
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401 || error.status === 403) {
console.log('The authentication session has expired or the user is not authorised. Redirecting to login page.');
this.router.navigate(['/login']);
}
}
});
}
}

谢谢。

最佳答案

就像 Marcel Lamothe 在他的回答中指出的那样,您可以通过克隆事件和更改 body 属性来更改响应。

import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(
private router: Router
) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// change the response body here
return event.clone({
body: 'myCustomResponse'
});
}

return event;
}).do((event: HttpEvent<any>) => {}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401 || error.status === 403) {
console.log('The authentication session has expired or the user is not authorised. Redirecting to login page.');
this.router.navigate(['/login']);
}
}
});
}
}

关于angular - 有什么方法可以改变 Angular 5 HttpInterceptor 中的响应吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47400364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com