Created
December 1, 2017 22:04
-
-
Save greyaperez/97ef00c423bd9296496e2f8d23e8faec to your computer and use it in GitHub Desktop.
Exposes Angular class members to the global namespace.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Expose Angular Methods | |
* @desc Exposes | |
* @private | |
* @param {string} namespace - Namespace to append to window.ng (ex: ng.WidgetComponent) | |
* @param {...string[]} member | |
* @example | |
* //////////////// | |
* // Usage Example | |
* //////////////// | |
* // Inside ngOnInit or constructor | |
* this.expose('WidgetComponent', 'someProp', 'anotherProp', 'someMethod', 'anotherMethod'); | |
* | |
* // Access Outside Angular | |
* ng.WidgetComponent.method1('hello', 'world'); // Angular Method | |
* ng.WidgetComponent.prop2; // Angular Prop | |
*/ | |
private expose(...members: string[]): void { | |
const namespace = this.constructor.name; | |
const exposeMethod = (member: string) => { | |
return (...args) => { | |
this.ngZone.run(() => { | |
if (typeof (this as any)[member] === 'function') { | |
return this[member](...args); | |
} else { | |
return; | |
} | |
}); | |
}; | |
}; | |
this.ngZone.runOutsideAngular(() => { | |
window.ng = (window.ng || {}); | |
window.ng[namespace] = {}; | |
// window.ng.getChartOptions = this.expose('getChartOptions'); | |
for (const member of members) { | |
if (typeof (this as any)[member] === 'function') { | |
window.ng[namespace][member] = exposeMethod(member).bind(this); | |
} else if (this.hasOwnProperty(member)) { | |
window.ng[namespace][member] = this[member]; | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment