Angular拦截器收到302响应的处理方法
创始人
2024-10-27 22:31:12
0
  1. 在Angular项目的拦截器中,可以通过使用rxjs的pipe操作符重新定义响应,以捕获重定向状态。可以通过以下代码示例实现:

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

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(request: HttpRequest, next: HttpHandler): Observable> { return next.handle(request).pipe( catchError((error: HttpErrorResponse) => { // 检查响应是 302 的重定向状态 if (error.status === 302) { // 处理重定向 // ... } else { return throwError(error); } }) ); } }

  1. 如果需要手动处理重定向,可以使用以下代码:

import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' }) export class MyService { constructor(private http: HttpClient) {}

performRequestWithRedirect(url: string, params: HttpParams): Observable { return this.http.get(url, { params, observe: 'response' }).pipe( map(response => { if (response.status === 302) { // 获取重定向位置 const redirectUrl = response.headers.get('Location') || ''; // 执行新的请求 return this.http.get(redirectUrl, { observe: 'response' }); } // 直接返回响应数据 return response; }) ); } }

在服务中使用performRequestWithRedirect方法,会处理重定向,同时返回响应数据。例如:

this.myService.performRequestWithRedirect('/some/url', new HttpParams()).subscribe(response => { console.log(response.body); });

相关内容

热门资讯

推荐透视!hhpoker辅助挂... 推荐透视!hhpoker辅助挂是真的吗,wpk有辅助器吗,妙计教程(有挂细节)-哔哩哔哩1、hhpo...
开挂透视!约局吧怎么看有没有挂... 开挂透视!约局吧怎么看有没有挂!原来一直总是有辅助工具(竟然有挂)-哔哩哔哩进入游戏-大厅左侧-新手...
详细透视!有没有人wepoke... 详细透视!有没有人wepoker,pokemmo修改器手机版,机巧教程(有挂技术)-哔哩哔哩1、下载...
揭露透视!佛手大菠萝辅助!本来... 揭露透视!佛手大菠萝辅助!本来有辅助插件(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正版游戏,...
科普透视!hhpoker怎么防... 科普透视!hhpoker怎么防作必弊,hhpoker免费透视脚本,积累教程(新版有挂)-哔哩哔哩1、...
普及透视!拱趴大菠萝怎么开挂!... 普及透视!拱趴大菠萝怎么开挂!果然真的是有辅助攻略(有挂技术)-哔哩哔哩1、游戏颠覆性的策略玩法,独...
解密透视!约局吧辅助器,wep... 解密透视!约局吧辅助器,wepoker怎么破解游戏,绝活儿教程(有挂规律)-哔哩哔哩1、wepoke...
分享透视!哈糖大菠萝破解器!总... 分享透视!哈糖大菠萝破解器!总是存在有辅助脚本(证实有挂)-哔哩哔哩1、哈糖大菠萝破解器辅助器安装包...
关于透视!wepoker透视方... 关于透视!wepoker透视方法,wpk透视插件,指南教程(真的有挂)-哔哩哔哩小薇(辅助器软件下载...
解密透视!德州局透视脚本下载安... 解密透视!德州局透视脚本下载安装最新版本!一直一直都是有辅助app(真实有挂)-哔哩哔哩德州局透视脚...