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

后端 未结 6 980
情话喂你
情话喂你 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:50

    Import the ActivatedRoute, (and the rest of the Router stuff too, if you want)

    import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router';
    

    making sure it's injected into the constructor,

    constructor(private route: ActivatedRoute) { ... }
    

    and on ngOnInit you can use this.route to inspect the URL. For instance, all the segments are in an array, which you can string together, as @ibgib suggested, like this:

    let path = this.route.snapshot.url.join('/');
    

    to give you something like "mars/moons/phobos".

提交回复
热议问题