Black Holes and
Angular Interceptors
with this guy:
About Me
- Google Developer Expert for Angular and Web Technologies
- Software Engineer at HeroDevs
- Organizer of Angular Bolivia community and NG Bolivia conference
- Open Source and Astrophotography enthusiast
Authentication Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
setToken(token: string) {
localStorage.setItem('token', token);
}
getToken() {
return localStorage.getItem('token');
}
}
Black Hole Interceptor
Powered by Angular
@Injectable({
providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler) {
const authRequest = request.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.getToken()}`
}
});
return next.handle(authRequest);
}
}
interceptors/index.ts
Powered by Angular
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptorService } from './auth-interceptor.service';
export const httpInterceptorProviders = [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptorService,
multi: true
},
];
app.module.ts
Powered by Angular
import { httpInterceptorProviders } from './shared/interceptors';
@NgModule({
declarations: [
AppComponent
],
imports: [...],
providers: [
httpInterceptorProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
Other use cases
- Custom Headers
- Logging
- Caching
- Loader Service
- General Notifications
- Error Handling
- Your own use case?