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

相关内容

热门资讯

据玩家消息!德州辅助工具到底怎... 据玩家消息!德州辅助工具到底怎么样(透视)微信小程序边锋辅助下载(竟然有辅助安装)-哔哩哔哩1、每一...
透视最新!红龙poker辅助平... 透视最新!红龙poker辅助平台(透视)鸿狐拼十辅助(果然真的有辅助插件)-哔哩哔哩1、起透看视 鸿...
为切实保障!wepoker辅助... 为切实保障!wepoker辅助是真的吗(透视)哈灵脚本修改器(确实是真的辅助修改器)-哔哩哔哩1、不...
透视了解!wepoker怎么挂... 透视了解!wepoker怎么挂底牌(透视)心悦辅助(原来存在有辅助软件)-哔哩哔哩1.心悦辅助 选牌...
为切实保障!wepoker手机... 为切实保障!wepoker手机插件(透视)川娱竞技辅助(一贯真的有辅助辅助器)-哔哩哔哩1、点击下载...
透视玄学!pokerrrr2辅... 透视玄学!pokerrrr2辅助(透视)微信插件激活码(真是真的是有辅助插件)-哔哩哔哩1、微信插件...
透视新版!拱趴大菠萝机器人(透... 透视新版!拱趴大菠萝机器人(透视)越乡游双扣辅助器(果然是真的辅助安装)-哔哩哔哩1、起透看视 越乡...
透视肯定!aapoker如何设... 透视肯定!aapoker如何设置胜率(透视)吉祥填大坑怎么用插件(果然真的有辅助神器)-哔哩哔哩1、...
无独有偶!fishpoker透... 无独有偶!fishpoker透视底牌(透视)新九游辅助软件(真是是真的辅助插件)-哔哩哔哩运新九游辅...
这一现象值得深思!德州局怎么透... 这一现象值得深思!德州局怎么透视(透视)微信小程序辅助有哪些(总是真的是有辅助辅助器)-哔哩哔哩1、...