After upgrading to the new version of Angular 8, I encountered an issue where the authorization token is not being sent in the request header for certain requests. Despite checking everything, the problem persists. When inspecting the console, I noticed that the authorization header is missing in some requests.
This code snippet demonstrates how to implement a RequestInterceptor in Angular:
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpEvent,
HttpHandler,
HttpRequest
} from '@angular/common/http';
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
req: HttpRequest,
next: HttpHandler
): Observable<HttpEvent> {
// Retrieve logged in user if connected
const userToken = this.authService.getAuthenticatedUser();
// Verify existing of the user
if (userToken != null && userToken.bearerToken != null) {
req = req.clone({
setHeaders: {
Authorization: userToken.bearerToken
}
});
}
return next.handle(req);
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
FooterComponent,
HomeComponent,
ContactUsComponent,
NotFoundComponent,
CartComponent,
LoginComponent
],
imports: [BrowserModule, AppRoutingModule, CustomModule, LayoutModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
Despite implementing the RequestInterceptor, the authorization header is still missing in some requests. Any help would be appreciated.