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

相关内容

热门资讯

透视脚本!aapoker透视脚... 透视脚本!aapoker透视脚本(透视)aapoker透视脚本,AI教程(有挂教程)运aapoker...
透视教程!wepoker线上大... 透视教程!wepoker线上大神,wepoker私人局辅助器怎么用(详细可以拿到好牌)1、游戏颠覆性...
透视透视!aapoker俱乐部... 透视透视!aapoker俱乐部靠谱吗(透视)aapoker辅助器是真的吗,AI教程(有挂揭秘)aap...
透视规律!WePoKer辅助器... 透视规律!WePoKer辅助器,poker辅助器免费安装(详细国外版透视)透视规律!WePoKer辅...
透视科技!aapoker脚本(... 透视科技!aapoker脚本(透视)aapoker能控制牌吗,wpk教程(有挂黑科技)aapoker...
透视好友房!wepoker辅助... 透视好友房!wepoker辅助工具,wepoker钻石怎么看底牌(详细有有挂规律)在进入wepoke...
透视存在!aapoker脚本(... 透视存在!aapoker脚本(透视)aapoker透视脚本,AI教程(有挂方法)1、金币登录送、破产...
透视安装!wepoker有辅助... 透视安装!wepoker有辅助工具吗,wepoker私人局规律(详细数据分析工具);wepoker有...
透视线上!aapoker透视脚... 透视线上!aapoker透视脚本下载(透视)aapoker辅助软件合法吗,插件教程(有挂解密);1、...
透视安卓版!wepoker辅助... 透视安卓版!wepoker辅助器,wepoker软件辅助程序(详细透视脚本免费)1、wepoker软...