I’m trying to learn Angular and I’m using version 17. I’ve reached the topic of interceptors, but no matter what I do, I can’t get the interceptor to work. The token doesn’t appear in the header response section. Here is the code
LoginComponent.ts
import { CommonModule } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, NgModule } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-login',
standalone: true,
imports: [CommonModule,
ReactiveFormsModule,
HttpClientModule,
],
templateUrl: './login.component.html',
styleUrl: './login.component.scss'
})
export class LoginComponent {
loginForm: FormGroup;
constructor(private formBuilder: FormBuilder, private http: HttpClient) {
this.loginForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
onSubmit() {
if (this.loginForm.valid) {
localStorage.setItem("token", "test1234")
this.http.post('https://jsonplaceholder.typicode.com/posts', this.loginForm.value)
.subscribe(
response => {
console.log('Login successful', response);
},
error => {
console.error('Login error', error);
}
);
} else {
console.log('Form is invalid');
}
}
}
app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { demoInterceptor } from './demo.interceptor';
import { provideClientHydration } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideHttpClient(withInterceptors([demoInterceptor])),
],
};
demo.interceptors.ts
import { HttpInterceptorFn } from '@angular/common/http';
export const demoInterceptor: HttpInterceptorFn = (req, next) => {
const authToken = localStorage.getItem("token");
// Clone the request and add the authorization header
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});
// Pass the cloned request with the updated header to the next handler
return next(authReq);
};
I tried all the solutions provided to similar issues on Stack Overflow, but none of them worked.
>Solution :
Remove the HttpClientModule import.
You’re overriding the interceptors on your component with this.