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国外版透视(AApoker万能)切实真的是有辅助插件(哔哩哔哩)1)wepo...
透视资料!德州来玩辅助器(We... 透视资料!德州来玩辅助器(WePoKer软件)果然真的有辅助攻略(哔哩哔哩)一、德州来玩辅助器可以开...
透视阶段!竞技联盟破解版最新版... 透视阶段!竞技联盟破解版最新版(HHpoker软件)竟然真的有辅助攻略(哔哩哔哩)一、竞技联盟破解版...
透视攻略!werplan外开挂... 透视攻略!werplan外开挂(WePoKer内容)本来存在有辅助方法(哔哩哔哩)1、werplan...
透视项目!wepoker透视破... 透视项目!wepoker透视破解版(HHpoker内部)切实真的是有辅助教程(哔哩哔哩)1)wepo...
透视操作!wepoker有用吗... 透视操作!wepoker有用吗(WePoKer内容)总是是有辅助app(哔哩哔哩)1、wepoker...
透视项目!哈糖大菠萝怎么挂(W... 透视项目!哈糖大菠萝怎么挂(WPK软件)一直是真的有辅助方法(哔哩哔哩)1、玩家可以在哈糖大菠萝怎么...
透视要领!哈糖大菠萝助手(We... 您好,哈糖大菠萝助手这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
透视步骤!德州私人局怎么透视(... 透视步骤!德州私人局怎么透视(WePoKer app)确实有辅助方法(哔哩哔哩)1、每一步都需要思考...
透视总结!wepoker免费脚... 透视总结!wepoker免费脚本咨询(WePoKer代打)一贯存在有辅助工具(哔哩哔哩)1、wepo...