要解决“Angular - 拦截器始终从localStorage获取accessToken时返回null值”的问题,可以按照以下步骤进行:
确保在登录时将accessToken存储在localStorage中。
创建一个AuthInterceptor拦截器,该拦截器将负责在每个请求上添加accessToken。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
const accessToken = localStorage.getItem('accessToken');
if (accessToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${accessToken}`
}
});
}
return next.handle(request);
}
}
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 {}
通过这些步骤,每当发出HTTP请求时,拦截器将从localStorage中获取accessToken并将其添加到请求的头部中。