global_event_srv.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import coreModule from 'app/core/core_module';
  2. import config from 'app/core/config';
  3. import appEvents from 'app/core/app_events';
  4. // This service is for registering global events.
  5. // Good for communication react > angular and vice verse
  6. export class GlobalEventSrv {
  7. private appSubUrl;
  8. private fullPageReloadRoutes;
  9. /** @ngInject */
  10. constructor(private $location, private $timeout, private $window) {
  11. this.appSubUrl = config.appSubUrl;
  12. this.fullPageReloadRoutes = ['/logout'];
  13. }
  14. // Angular's $location does not like <base href...> and absolute urls
  15. stripBaseFromUrl(url = '') {
  16. const appSubUrl = this.appSubUrl;
  17. const stripExtraChars = appSubUrl.endsWith('/') ? 1 : 0;
  18. const urlWithoutBase =
  19. url.length > 0 && url.indexOf(appSubUrl) === 0
  20. ? url.slice(appSubUrl.length - stripExtraChars)
  21. : url;
  22. return urlWithoutBase;
  23. }
  24. init() {
  25. appEvents.on('location-change', payload => {
  26. const urlWithoutBase = this.stripBaseFromUrl(payload.href);
  27. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  28. this.$window.location.href = payload.href;
  29. return;
  30. }
  31. this.$timeout(() => {
  32. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  33. this.$location.url(urlWithoutBase);
  34. });
  35. });
  36. }
  37. }
  38. coreModule.service('globalEventSrv', GlobalEventSrv);