How to get the current url in the browser in Angular 2 using TypeScript?

后端 未结 6 1012
情话喂你
情话喂你 2020-12-05 23:34

I need to get the current URL present in the browser in my Angular 2 application.

In JavaScript normally we do it using the window object.

How can I do this

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 23:37

    It is not necessary to import complicated packages or inject something. Just use the methods you can find on window.location!

    Such as:

    • window.location.href gives you the full URL
    • window.location.hostname gives you the host name
    • window.location.originwith this command you get the host name with protocol (e.g. https://)
    • and more as you can see here: click me

    For IE<=10 users: location.origin may not be available, then you have to use location.protocol + "//" + location.hostname or use a polyfill or package like location-origin

提交回复
热议问题