bridge_srv.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // some state changes should not trigger new browser history
  45. if (state.location.replace) {
  46. this.$location.replace();
  47. }
  48. });
  49. console.log('store updating angular $location.url', url);
  50. }
  51. });
  52. appEvents.on('location-change', payload => {
  53. const urlWithoutBase = locationUtil.stripBaseFromUrl(payload.href);
  54. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  55. this.$window.location.href = payload.href;
  56. return;
  57. }
  58. this.$timeout(() => {
  59. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  60. this.$location.url(urlWithoutBase);
  61. });
  62. });
  63. }
  64. }
  65. coreModule.service('bridgeSrv', BridgeSrv);