DEV Community

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

Posted on

3 1

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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay