Skip to content

Instantly share code, notes, and snippets.

@edewit
Last active June 18, 2018 11:39
Show Gist options
  • Save edewit/2370f51ff7966a9727357357085a562f to your computer and use it in GitHub Desktop.
Save edewit/2370f51ff7966a9727357357085a562f to your computer and use it in GitHub Desktop.
import * as _ from 'lodash';
import { Broadcaster } from 'ngx-base';
import { Injector } from '@angular/core';
export function broadcast(event: string, properties: any): MethodDecorator {
return function (target: Function, methodName: string, descriptor: any) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const broadcast: Broadcaster = StaticInjector.injector.get(Broadcaster);
if (!broadcast) {
return originalMethod.apply(this, args);
}
const mapKeys = (props: any, base?: string): any => {
Object.keys(props).forEach(key => {
if (typeof properties[key] === 'object') {
mapKeys(properties[key], key);
} else {
properties[key] = _.get(this, (base || '') + '.' + properties[base][key]);
}
});
};
let props = _.cloneDeep(properties);
mapKeys(props);
broadcast.broadcast(event, props);
return originalMethod.apply(this, args);
};
return descriptor;
};
}
export class StaticInjector {
static injector: any = null;
constructor(injector: Injector) {
StaticInjector.injector = injector;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment