bridge_srv.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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) {
  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());
  28. }
  29. });
  30. this.$rootScope.$on('$routeChangeSuccess', (evt, data) => {
  31. let angularUrl = this.$location.url();
  32. if (store.view.currentUrl !== angularUrl) {
  33. store.view.updatePathAndQuery(this.$location.path(), this.$location.search());
  34. }
  35. });
  36. reaction(
  37. () => store.view.currentUrl,
  38. currentUrl => {
  39. let angularUrl = this.$location.url();
  40. if (angularUrl !== currentUrl) {
  41. this.$location.url(currentUrl);
  42. console.log('store updating angular $location.url', currentUrl);
  43. }
  44. }
  45. );
  46. appEvents.on('location-change', payload => {
  47. const urlWithoutBase = this.stripBaseFromUrl(payload.href);
  48. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  49. this.$window.location.href = payload.href;
  50. return;
  51. }
  52. this.$timeout(() => {
  53. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  54. this.$location.url(urlWithoutBase);
  55. });
  56. });
  57. }
  58. }
  59. coreModule.service('bridgeSrv', BridgeSrv);