在Angular中使用HTTP拦截器来添加身份验证头部是一个常见的做法。下面是一个简单的示例,演示如何在Angular中实现这一点:
auth.interceptor.ts
的文件,用于定义HTTP拦截器。import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 获取存储在本地的身份验证令牌
const authToken = localStorage.getItem('authToken');
// 克隆请求并添加身份验证头部
const authRequest = request.clone({
headers: request.headers.set('Authorization', `Bearer ${authToken}`)
});
// 继续处理请求
return next.handle(authRequest);
}
}
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
export class AppModule { }
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent {
constructor(private http: HttpClient) { }
getData() {
this.http.get('/api/data').subscribe(response => {
console.log(response);
});
}
}
在以上示例中,我们创建了一个名为AuthInterceptor
的HTTP拦截器。在intercept
方法中,我们从本地存储中获取身份验证令牌,并将其添加到请求的头部中。然后,我们使用HTTP_INTERCEPTORS
提供程序在模块中注册拦截器。最后,在组件中使用HttpClient
发送HTTP请求,拦截器将自动添加身份验证头部。