bridge_srv.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import coreModule from 'app/core/core_module';
  2. import config from 'app/core/config';
  3. import appEvents from 'app/core/app_events';
  4. import { store } from 'app/stores/store';
  5. import { reaction } from 'mobx';
  6. // Services that handles angular -> mobx store sync & other react <-> angular sync
  7. export class BridgeSrv {
  8. private appSubUrl;
  9. private fullPageReloadRoutes;
  10. /** @ngInject */
  11. constructor(private $location, private $timeout, private $window, private $rootScope, private $route) {
  12. this.appSubUrl = config.appSubUrl;
  13. this.fullPageReloadRoutes = ['/logout'];
  14. }
  15. // Angular's $location does not like <base href...> and absolute urls
  16. stripBaseFromUrl(url = '') {
  17. const appSubUrl = this.appSubUrl;
  18. const stripExtraChars = appSubUrl.endsWith('/') ? 1 : 0;
  19. const urlWithoutBase =
  20. url.length > 0 && url.indexOf(appSubUrl) === 0 ? url.slice(appSubUrl.length - stripExtraChars) : url;
  21. return urlWithoutBase;
  22. }
  23. init() {
  24. this.$rootScope.$on('$routeUpdate', (evt, data) => {
  25. let angularUrl = this.$location.url();
  26. if (store.view.currentUrl !== angularUrl) {
  27. store.view.updatePathAndQuery(this.$location.path(), this.$location.search(), this.$route.current.params);
  28. }
  29. });
  30. this.$rootScope.$on('$routeChangeSuccess', (evt, data) => {
  31. store.view.updatePathAndQuery(this.$location.path(), this.$location.search(), this.$route.current.params);
  32. });
  33. reaction(
  34. () => store.view.currentUrl,
  35. currentUrl => {
  36. let angularUrl = this.$location.url();
  37. if (angularUrl !== currentUrl) {
  38. this.$timeout(() => {
  39. this.$location.url(currentUrl);
  40. });
  41. console.log('store updating angular $location.url', currentUrl);
  42. }
  43. }
  44. );
  45. appEvents.on('location-change', payload => {
  46. const urlWithoutBase = this.stripBaseFromUrl(payload.href);
  47. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  48. this.$window.location.href = payload.href;
  49. return;
  50. }
  51. this.$timeout(() => {
  52. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  53. this.$location.url(urlWithoutBase);
  54. });
  55. });
  56. }
  57. }
  58. coreModule.service('bridgeSrv', BridgeSrv);