Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. var thunkDispatcherRef = {
  2. dispatch: function () {}
  3. }
  4.  
  5. /**
  6. * The angular injection middleware allows our redux actions to return functions.
  7. *
  8. * The function will be executed with regular angular dependency injection, allowing
  9. * you to use angular services in Redux actions.
  10. *
  11. * The redux-thunk also operates on actions that return functions. We interact with
  12. * thunk by: 1) Adding a provider for the `dispatch` function used by thunk. 2) Carefully
  13. * checking the arguments, and if a `dispatch` argument exists, passing redux-thunk a
  14. * function that will correctly execute the angular function with the new dispatch funcion.
  15. */
  16. function angularInjectionMiddleware($injector) {
  17. return store => next => action => {
  18. if (typeof action === 'function') {
  19. let injectionsRequired = $injector.annotate(action);
  20. if (injectionsRequired.indexOf('dispatch') > -1) {
  21. if (injectionsRequired.length === 1) {
  22. // Only a dispatch action, pass directly on to redux-thunk.
  23. next(action);
  24. } else {
  25. // We need to run `next`, which will be with redux-thunk.
  26. // This will give us the dispatch method, which we can then use in angular injection.
  27. let actionForThunk = function (dispatch) {
  28. thunkDispatcherRef.dispatch = dispatch;
  29. return $injector.invoke(action);
  30. }
  31. return next(actionForThunk)
  32. }
  33. } else {
  34. // Angular action only, with no `dispatch` argument, so we can return a value and ignore thunk.
  35. return next($injector.invoke(action));
  36. }
  37.  
  38. } else {
  39. return next(action);
  40. }
  41. }
  42. }
  43.  
  44. angular.module('myApp').factory('dispatch', function () {
  45. return thunkDispatcherRef.dispatch;
  46. });
  47.  
  48. angular.module('myApp').factory('angularInjectionMiddleware', angularInjectionMiddleware);
  49.  
  50. export default angularInjectionMiddleware;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement