Last active
May 24, 2020 22:21
-
-
Save gskachkov/4af6681c5a626dea4c96c458b5f6838f to your computer and use it in GitHub Desktop.
Decorator for async function in angular
This file contains hidden or 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
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; |
This file contains hidden or 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
class DecoratorHelper { | |
get injector() { | |
return this.injectorInstance; | |
} | |
set injector(injector) { | |
this.injectorInstance = injector; | |
} | |
} | |
const helper = new DecoratorHelper(); | |
export default helper; |
This file contains hidden or 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
// 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