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); });

相关内容

热门资讯

透视大纲!wepoker究竟有... 透视大纲!wepoker究竟有没有透视(WePoKer正版)果然存在有辅助教程(哔哩哔哩)一、wep...
透视模块!聚星ai辅助工具激活... 透视模块!聚星ai辅助工具激活码(透视)pokemmo辅助脚本(辅助)果然一直都是有脚本(哔哩哔哩)...
透视方式!wepoker游戏安... 透视方式!wepoker游戏安装教程(WePoKer分析器)总是真的有辅助技巧(哔哩哔哩);1、下载...
透视资料!菠萝辅助器免费版的功... 透视资料!菠萝辅助器免费版的功能介绍(透视)福建大菠萝万能辅助器(辅助)一贯是真的有脚本(哔哩哔哩)...
透视窍要!哈糖大菠萝可以开挂吗... 透视窍要!哈糖大菠萝可以开挂吗(WPK控制牌)都是真的有辅助工具(哔哩哔哩)1、该软件可以轻松地帮助...
透视模块!hhpoker是真的... 透视模块!hhpoker是真的吗(HHpoker机器人)本来是真的有辅助技巧(哔哩哔哩)在进入hhp...
透视诀窍!epoker有透视吗... 透视诀窍!epoker有透视吗(透视)pokemmo修改器手机版(辅助)真是真的是有教程(哔哩哔哩)...
透视学习!wepokerplu... 透视学习!wepokerplus到底是挂了吗(WePoKer价格)好像是真的有辅助脚本(哔哩哔哩)1...
透视教程书!德州透视竞技联盟(... 透视教程书!德州透视竞技联盟(透视)pokerworld软件(辅助)真是一直总是有app(哔哩哔哩)...
透视模板!wepoker有脚本... 透视模板!wepoker有脚本吗(WePoKer私人局)真是存在有辅助攻略(哔哩哔哩)一、wepok...