How to get base url in angular 5?

前端 未结 9 923
抹茶落季
抹茶落季 2020-12-06 04:01

My current url is http://localhost:4200/test/dashboard.

I want to print base url i.e http://localhost:4200 using angular 5 features.

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 04:37

    import { DOCUMENT, LocationStrategy } from '@angular/common';
    
    
    @Injectable()
    export class SomeService {
      constructor(@Inject(DOCUMENT) private readonly document: any,
        private readonly locationStrategy: LocationStrategy) {}
    
      // for localhost: http://localhost:4200/someBaseHref
      getUrl(): string {
        return `${this.document.location.origin}/${this.locationStrategy.getBaseHref()}`
      }
    
    }
    

提交回复
热议问题