DEV Community

Cover image for Colorize your routes in Angular with a simple interceptor.
ElAndyG
ElAndyG

Posted on

Colorize your routes in Angular with a simple interceptor.

live example

We know the simplest way to view traffic is using the network tab in DevTools, but sometimes you need to add another tool to your debugging arsenal. Using an interceptor will help you tap into the http request pipeline so you can work your magic and log all of your routes in a nice color-coded format so they stand out.

If you are using the In-Memory Web API, (which is the best thing since sliced bread), all of your calls are technically not going over the wire, so nothing is written to the network tab. Adding this interceptor also will help replace it until you are ready to move over to live data.

Here it is! A tiny bit of code to help you out. Be sure to try it out on StackBlitz, and remember to remove it before you go live 😀.

@Injectable()
export class LogAndColorizeRoutesInterceptor implements HttpInterceptor {
  constructor(private jsonPipe: JsonPipe) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (req.url.startsWith('api')) {
      const body = req.body ? ': ' + this.jsonPipe.transform(req.body) : '';
      console.log(
        `%c${req.method} ${req.url}${body}`,
        this.getColor(req.method)
      );
    }
    return next.handle(req);
  }

  getColor(method: string): string {
    switch (method) {
      case 'PUT':
        return 'color: #fca130';
      case 'GET':
        return 'color: #61affe';
      case 'POST':
        return 'color: #49cc90';
      case 'DELETE':
        return 'color: #f93e3e';
      case 'PATCH':
        return 'color: #b7410e';
      default:
        return 'color: #000000';
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Result:
Chrome Console

Top comments (0)