Search code examples
angularangular-router

Angular 6: Get base href


I would like to get in angular 6 component. I managed it by: PlatformLocation#getBaseHrefFromDOM.

But this api should not be used by developers. Is there any other way to get /CTX-ROOT/assets/tiny-editor/langs/cs.js in runtime?

  constructor(
    private zone: NgZone,
    private platformLocation: PlatformLocation) {
  }

  public ngAfterViewInit() {
    var baseHref = this.platformLocation.getBaseHrefFromDOM();
    Observable.fromPromise(tinymce.init({
      selector: '#' + this.elementId,
      entity_encoding: "raw",
      menubar: false,
      branding: false,
      elementpath: true,
      language_url: baseHref + '/assets/tiny-editor/langs/cs.js',

Solution

  • You can use the prepareExternalUrl method from the Location service (doc)

    import {Location} from "@angular/common";
    
    //...
    constructor(
        private zone: NgZone,
        private location: Location) {
    }
    
    
    public ngAfterViewInit() {
        Observable.fromPromise(tinymce.init({
          selector: '#' + this.elementId,
          entity_encoding: "raw",
          menubar: false,
          branding: false,
          elementpath: true,
          language_url: this.location.prepareExternalUrl('assets/tiny-editor/langs/cs.js')
    

    Edit: I assume this only works when using PathLocationStrategy

    This method will also add a hash if HashLocationStrategy is used, or the APP_BASE_HREF if the PathLocationStrategy is in use.