Logging observable accessors

Let’s say you’ve moving observables around in a service.

get somethingCount$() {
    return this.otherService.somethingCount$;
  }

You want to log the result passed forwards, and you hate writing the tap operator.

Usage & Decorator

It would look a lot cleaner and a lot more verbose (in a good way) with a decorator!

@logObservable
get somethingCount$() {
    return this.otherService.somethingCount$;
  }

Here’s the decorator:

import { tap } from 'rxjs/operators';

export const logObservable = (
  target,
  propertyKey: string,
  descriptor: PropertyDescriptor,
) => {
  const orig = descriptor.get;
  descriptor.get = function () {
    return orig.call(this).pipe(
      tap(val => {
          console.log(`[${propertyKey}]`, val);
        }
      )
    );
  };
};

NOTE: Always use function () { for the getter accessor if you want to change the decorator.

if using orig.call(target) in Angular, this.otherService in this example returns undefined.