bridge_srv.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import coreModule from 'app/core/core_module';
  2. import appEvents from 'app/core/app_events';
  3. import { store } from 'app/store/store';
  4. import locationUtil from 'app/core/utils/location_util';
  5. import { updateLocation } from 'app/core/actions';
  6. // Services that handles angular -> redux store sync & other react <-> angular sync
  7. export class BridgeSrv {
  8. private fullPageReloadRoutes;
  9. /** @ngInject */
  10. constructor(private $location, private $timeout, private $window, private $rootScope, private $route) {
  11. this.fullPageReloadRoutes = ['/logout'];
  12. }
  13. init() {
  14. this.$rootScope.$on('$routeUpdate', (evt, data) => {
  15. const angularUrl = this.$location.url();
  16. const state = store.getState();
  17. if (state.location.url !== angularUrl) {
  18. store.dispatch(
  19. updateLocation({
  20. path: this.$location.path(),
  21. query: this.$location.search(),
  22. routeParams: this.$route.current.params,
  23. })
  24. );
  25. }
  26. });
  27. this.$rootScope.$on('$routeChangeSuccess', (evt, data) => {
  28. store.dispatch(
  29. updateLocation({
  30. path: this.$location.path(),
  31. query: this.$location.search(),
  32. routeParams: this.$route.current.params,
  33. })
  34. );
  35. });
  36. // Listen for changes in redux location -> update angular location
  37. store.subscribe(() => {
  38. const state = store.getState();
  39. const angularUrl = this.$location.url();
  40. const url = locationUtil.stripBaseFromUrl(state.location.url);
  41. if (angularUrl !== url) {
  42. this.$timeout(() => {
  43. this.$location.url(url);
  44. });
  45. console.log('store updating angular $location.url', url);
  46. }
  47. });
  48. appEvents.on('location-change', payload => {
  49. const urlWithoutBase = locationUtil.stripBaseFromUrl(payload.href);
  50. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  51. this.$window.location.href = payload.href;
  52. return;
  53. }
  54. this.$timeout(() => {
  55. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  56. this.$location.url(urlWithoutBase);
  57. });
  58. });
  59. }
  60. }
  61. coreModule.service('bridgeSrv', BridgeSrv);