Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法改变Angular 5 HttpInterceptor的响应?_Angular_Typescript_Rxjs_Angular Httpclient - Fatal编程技术网

有没有办法改变Angular 5 HttpInterceptor的响应?

有没有办法改变Angular 5 HttpInterceptor的响应?,angular,typescript,rxjs,angular-httpclient,Angular,Typescript,Rxjs,Angular Httpclient,对于我的应用程序,我创建了以下HttpInterceptor。有没有办法从这里向请求订阅者返回修改后的响应版本 import { Injectable } from '@angular/core'; import { HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } fr

对于我的应用程序,我创建了以下
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']);
                }
            }
        });
    }
}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpRequest,HttpResponse,HttpErrorResponse,HttpHandler,HttpEvent,HttpInterceptor};
从“rxjs/Observable”导入{Observable};
从'@angular/Router'导入{Router};
@可注射()
导出类RequestInterceptor实现HttpInterceptor{
建造师(
专用路由器
) { }
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
返回next.handle(request).do((事件:HttpEvent)=>{
if(HttpResponse的事件实例){
//有没有办法改变发送给请求订阅者的响应?
}
},(错误:any)=>{
if(HttpErrorResponse的错误实例){
if(error.status==401 | | error.status==403){
console.log('身份验证会话已过期或用户未经授权。正在重定向到登录页面');
this.router.navigate(['/login']);
}
}
});
}
}

谢谢。

请参阅Http指南的不变性部分:

拦截器的存在是为了检查和改变传出的请求和传入的响应。然而,了解到HttpRequest和HttpResponse类在很大程度上是不可变的,这可能会令人惊讶

这是有原因的:因为应用程序可能会重试请求,所以拦截器链可能会多次处理单个请求。如果请求是可变的,则重试的请求将不同于原始请求。不变性确保拦截器在每次尝试中看到相同的请求

有一种情况是,在将拦截器写入请求主体时,类型安全性无法保护您。在拦截器中改变请求主体是无效的,但类型系统不会对此进行检查

如果需要修改请求正文,则需要复制请求正文,修改副本,然后使用clone()复制请求并设置新正文

因为请求是不可变的,所以不能直接修改它们。要对它们进行变异,请使用clone()


正如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/core'导入{Injectable};
从'@angular/common/http'导入{HttpRequest,HttpResponse,HttpErrorResponse,HttpHandler,HttpEvent,HttpInterceptor};
从“rxjs/Observable”导入{Observable};
从'@angular/Router'导入{Router};
@可注射()
导出类RequestInterceptor实现HttpInterceptor{
建造师(
专用路由器
) {}
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
返回next.handle(request.map)((事件:HttpEvent)=>{
if(HttpResponse的事件实例){
//在这里更改响应主体
return event.clone({
正文:“myCustomResponse”
});
}
返回事件;
}).do((事件:HttpEvent)=>{},(错误:any)=>{
if(HttpErrorResponse的错误实例){
if(error.status==401 | | error.status==403){
console.log('身份验证会话已过期或用户未经授权。正在重定向到登录页面');
this.router.navigate(['/login']);
}
}
});
}
}