bridge_srv.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. import { ITimeoutService, ILocationService, IWindowService, IRootScopeService } from 'angular';
  7. // Services that handles angular -> redux store sync & other react <-> angular sync
  8. export class BridgeSrv {
  9. private fullPageReloadRoutes: string[];
  10. /** @ngInject */
  11. constructor(
  12. private $location: ILocationService,
  13. private $timeout: ITimeoutService,
  14. private $window: IWindowService,
  15. private $rootScope: IRootScopeService,
  16. private $route: any
  17. ) {
  18. this.fullPageReloadRoutes = ['/logout'];
  19. }
  20. init() {
  21. this.$rootScope.$on('$routeUpdate', (evt, data) => {
  22. const angularUrl = this.$location.url();
  23. const state = store.getState();
  24. if (state.location.url !== angularUrl) {
  25. store.dispatch(
  26. updateLocation({
  27. path: this.$location.path(),
  28. query: this.$location.search(),
  29. routeParams: this.$route.current.params,
  30. })
  31. );
  32. }
  33. });
  34. this.$rootScope.$on('$routeChangeSuccess', (evt, data) => {
  35. store.dispatch(
  36. updateLocation({
  37. path: this.$location.path(),
  38. query: this.$location.search(),
  39. routeParams: this.$route.current.params,
  40. })
  41. );
  42. });
  43. // Listen for changes in redux location -> update angular location
  44. store.subscribe(() => {
  45. const state = store.getState();
  46. const angularUrl = this.$location.url();
  47. const url = locationUtil.stripBaseFromUrl(state.location.url);
  48. if (angularUrl !== url) {
  49. this.$timeout(() => {
  50. this.$location.url(url);
  51. // some state changes should not trigger new browser history
  52. if (state.location.replace) {
  53. this.$location.replace();
  54. }
  55. });
  56. console.log('store updating angular $location.url', url);
  57. }
  58. });
  59. appEvents.on('location-change', (payload: any) => {
  60. const urlWithoutBase = locationUtil.stripBaseFromUrl(payload.href);
  61. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  62. this.$window.location.href = payload.href;
  63. return;
  64. }
  65. this.$timeout(() => {
  66. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  67. this.$location.url(urlWithoutBase);
  68. });
  69. });
  70. }
  71. }
  72. coreModule.service('bridgeSrv', BridgeSrv);