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

后端 未结 5 2043
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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

提交回复
热议问题