Angular 5: 在拦截器中从HTTP响应头部获取授权
创始人
2024-10-15 22:01:18
0

在Angular 5中,你可以通过创建一个拦截器来从HTTP响应头部获取授权信息。下面是一个示例代码:

首先,创建一个新的HTTP拦截器,在该拦截器中获取授权信息:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    // 获取授权信息
    const authToken = localStorage.getItem('authToken');

    // 克隆原始请求并添加授权头部
    const authReq = request.clone({
      headers: request.headers.set('Authorization', authToken)
    });

    // 继续处理请求
    return next.handle(authReq);
  }
}

然后,在你的AppModule中注册拦截器:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [AppComponent],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

在上面的代码中,我们将AuthInterceptor注册为HTTP_INTERCEPTORS提供者,并设置multi为true,以便将其添加到现有的拦截器列表中。

现在,每当你发出HTTP请求时,拦截器将在请求中添加授权头部,以便从响应头部获取授权信息。

相关内容

热门资讯

透视科普!wepoker有人用... 透视科普!wepoker有人用过吗(透视)拱趴大菠萝挂怎么安装,教程方式(有挂方针)-哔哩哔哩该软件...
pokemomo辅助软件!we... pokemomo辅助软件!wepoker有透视功能吗(透视)神器-真是揭露是真的挂1)wepoker...
透视开挂!哈糖大菠萝助手(透视... 透视开挂!哈糖大菠萝助手(透视)德普之星透视辅助软件下载,教程攻略(有挂教程)-哔哩哔哩1、很好的工...
wejoker透视方法!菠萝辅... wejoker透视方法!菠萝辅助器免费版的特点(透视)工具-一直普及有挂1、菠萝辅助器免费版的特点有...
透视推荐!aapoker怎么开... 透视推荐!aapoker怎么开辅助器(透视)wpk德州局透视,教程阶段(今日头条)-哔哩哔哩1、aa...
德州圈脚本!hhpoker可以... 德州圈脚本!hhpoker可以控制吗(透视)教程-一贯解迷是真的挂1、在hhpoker可以控制吗插件...
透视有挂!wepoker私局辅... 透视有挂!wepoker私局辅助(透视)wepoker有脚本吗,教程指南(有挂讲解)-哔哩哔哩1、下...
wepoker脚本!德州透视h... wepoker脚本!德州透视hhpoker(透视)器-切实解密真的有挂wepoker脚本!德州透视h...
pokemmo辅助工具!德普之... pokemmo辅助工具!德普之星透视辅助软件激活码(透视)挂-原来透视有挂一、德普之星透视辅助软件激...
透视有挂!wepoker买脚本... 透视有挂!wepoker买脚本靠谱吗(透视)约局吧开挂神器是真的吗,教程要领(有挂方略)-哔哩哔哩1...