global_event_srv.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 ? url.slice(appSubUrl.length - stripExtraChars) : url;
  20. return urlWithoutBase;
  21. }
  22. init() {
  23. appEvents.on('location-change', payload => {
  24. const urlWithoutBase = this.stripBaseFromUrl(payload.href);
  25. if (this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
  26. this.$window.location.href = payload.href;
  27. return;
  28. }
  29. this.$timeout(() => {
  30. // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
  31. this.$location.url(urlWithoutBase);
  32. });
  33. });
  34. }
  35. }
  36. coreModule.service('globalEventSrv', GlobalEventSrv);