How do I get the absolute path of the current page in Angular 2?

后端 未结 5 2015
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 06:34

I\'ve essentially run into this problem, where I need a reference to the current route to use gradients, but have yet to figure out how to translate the solution into Angula

相关标签:
5条回答
  • 2020-11-30 07:06

    With base href:

    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()}`
      }
    
    }
    
    0 讨论(0)
  • 2020-11-30 07:13

    if you reload page , you can not get route path by Router or ActivatedRoute . You should use window.location.pathname

    0 讨论(0)
  • 2020-11-30 07:14

    You can use the DOCUMENT injection from @angular/common.

    import { Component, Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    
    @Component({...})
    class SomeComponent {
      constructor(@Inject(DOCUMENT) document: any) {
        console.log(document.location.href);
      }
    }
    
    0 讨论(0)
  • 2020-11-30 07:22
    constructor(location:Location) {
      console.log(location.prepareExternalUrl(location.path()));
    }
    

    https://angular.io/api/common/Location#prepareexternalurl

    As the documentation says:

    Normalizes an external URL path. If the given URL doesn't begin with a leading slash ('/'), adds one before normalizing. Adds a hash if HashLocationStrategy is in use, or the APP_BASE_HREF if the PathLocationStrategy is in use.

    It means that you have to explicitly specify APP_BASE_HREF to get an absolute path in Angular 5+.

    window.location provides more information

    Plunker example

    0 讨论(0)
  • 2020-11-30 07:22

    Location object

    The document.location object is your one stop solution.

    Use the attributes inside location object from document to get the path in the way you need. Let's see this with an example.

    So for https://www.google.com/images

    • document.location.href will return https://www.google.com/images
    • document.location.origin will return https://www.google.com
    • document.location.protocol will return https:
    • document.location.host will return google.com
    • document.location.hostname will return google
    • document.location.pathname will return /images
    0 讨论(0)
提交回复
热议问题