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如何设置透视,都是是有挂(有人有挂)1、免费脚...
玩家必看秘籍!we-poker... 玩家必看秘籍!we-poker软件,wepoker怎么看牌型,其实是真的有挂(果真有挂)1、金币登录...
玩家攻略推荐!竞技联盟透视,h... 玩家攻略推荐!竞技联盟透视,hhpoker怎么开透视,真是真的有挂(揭秘有挂)1、游戏颠覆性的策略玩...
玩家必备教程!德州hhpoke... 玩家必备教程!德州hhpoker是真的吗,hhpoker免费透视脚本,一直存在有挂(有挂教程)1、每...
我来教大家!we poker辅... 我来教大家!we poker辅助器,wepoker怎么发冤家牌,都是是有挂(有挂头条)1、有没有辅助...
必备教程!wepokerplu... 必备教程!wepokerplus透视脚本免费,wepoker有没有挂,本来是真的有挂(竟然有挂)1、...
玩家必备科普!红龙poker辅... 玩家必备科普!红龙poker辅助,wepoker新号好一点吗,原来真的有挂(有挂详情)1、实时透视辅...
今日公布!wpk透视工作室,p... 今日公布!wpk透视工作室,pokemmo手机版脚本免费,原来是有挂(有挂解惑)1、脚本辅助下载、免...
每日必看教程!xpoker辅助... 每日必看教程!xpoker辅助,hhpoker为什么一直输,果然真的有挂(有挂总结)1、首先打开辅助...
玩家亲测!大菠萝辅助器,约局吧... 玩家亲测!大菠萝辅助器,约局吧德州有挂吗,真是存在有挂(有挂方略)1、大菠萝辅助器有没有辅助教程、大...