Black Holes and Angular Interceptors

with this guy:


About Me



What is a Black Hole?

Angular Interceptors

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



Resources



Thank You!