How to get base url in angular 5?

前端 未结 9 922
抹茶落季
抹茶落季 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:44

    This doesn't work for me (Angular 7):

    this.location.path.name
    

    But I found that it's possible to get it from document:

    import { Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    
    constructor(@Inject(DOCUMENT) private document: Document) {
        const origin = this.document.location.origin;
    }
    
    0 讨论(0)
  • 2020-12-06 04:50

    PlatformLocation provides more details about the URL:

    import {PlatformLocation } from '@angular/common';
    
     constructor(platformLocation: PlatformLocation) {
      console.log((platformLocation as any).location);
      console.log((platformLocation as any).location.href);
      console.log((platformLocation as any).location.origin);
    }
    
    0 讨论(0)
  • 2020-12-06 04:52

    You can import 'Location' from the 'common' package:

    import { Component, OnInit } from '@angular/core';
    import { Location } from '@angular/common'; // <--- Here
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'some-component',
      templateUrl: './component.html',
      styleUrls: ['./component.scss']
    })
    export class SomeComponent implements OnInit {
    
      constructor(location: Location) {}
    
      ngOnInit() {
            console.log(this.location.origin);  // <--- Use Here
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题