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可以透视码(透视)微乐小程序辅助器免费安卓(原来有辅助修改器)-哔哩哔哩1、...
目前!aapoker怎么控制牌... 目前!aapoker怎么控制牌(透视)陕麻圈黑科技(都是真的是有辅助神器)-哔哩哔哩1、陕麻圈黑科技...
网友热议!hhpoker买挂(... 网友热议!hhpoker买挂(透视)越乡游义乌辅助器下载(真是是真的辅助工具)-哔哩哔哩1、许多玩家...
透视ai代打!pokemmo辅... 透视ai代打!pokemmo辅助器手机版下载(透视)桂林老k字字牌辅助(果然是真的辅助下载)-哔哩哔...
透视ai代打!wepoker透... 透视ai代打!wepoker透视有用吗(透视)hhpoker免费辅助器(本来是真的辅助插件)-哔哩哔...
透视插件!佛手大菠萝13道挂哪... 透视插件!佛手大菠萝13道挂哪里(透视)拱趴辅助器(一贯有辅助神器)-哔哩哔哩1、打开软件启动之后找...
透视系统!竞技联盟辅助(透视)... 透视系统!竞技联盟辅助(透视)新漫游免费辅助器(果然存在有辅助平台)-哔哩哔哩新漫游免费辅助器脚本下...
记者获悉!pokermaste... 记者获悉!pokermaster修改器(透视)八闽福建辅助软件免费下载(一贯存在有辅助插件)-哔哩哔...
透视真的!wepoker有没有... 透视真的!wepoker有没有机器人(透视)兴动互娱游戏辅助器(一贯是真的辅助软件)-哔哩哔哩1.兴...
辅助透视!wepoker透视版... 辅助透视!wepoker透视版下载(透视)洞庭茶苑辅助(其实是有辅助工具)-哔哩哔哩在进入洞庭茶苑辅...