Skip to content

Instantly share code, notes, and snippets.

@gskachkov
Last active May 24, 2020 22:21
Show Gist options
  • Save gskachkov/4af6681c5a626dea4c96c458b5f6838f to your computer and use it in GitHub Desktop.
Save gskachkov/4af6681c5a626dea4c96c458b5f6838f to your computer and use it in GitHub Desktop.
Decorator for async function in angular
import decoratorHelper from 'decorator.helper';
// Current decorator allow async function to be used in angular
// without adding unnecessary digest calls
const ngAync = function () {
return function (target, key, descriptor) {
const fn = descriptor.value;
descriptor.value = function () {
const result = fn.apply(this, arguments);
// To work our decorator we need injector, but we
// managed to access $injectro only from angular.run
// function
const $injector = decoratorHelper.injector;
$injector.invoke(($rootScope, $q) => {
'ngInject';
// Force new digest
$q.when(result)
.then(() => $rootScope.$applyAsync());
});
};
};
};
export default ngAync;
class DecoratorHelper {
get injector() {
return this.injectorInstance;
}
set injector(injector) {
this.injectorInstance = injector;
}
}
const helper = new DecoratorHelper();
export default helper;
// Load module to register run handler, where we store
// $injector
import angularModule from 'currentAngularModule';
import decoratorHelper from 'decorator.helper';
angularModule.run($injector => {
'ngInject';
// Store injector in helper, it will be used by
// decorators to invisible integration of decorators
// with Angular
decoratorHelper.injector = $injector;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment