Location is a service available in Angular 2+ apps that makes it easy to interact with the current URL path. For most navigation needs, the Angular router is the correct solution, but in a few cases the location service is needed to affect the url without involving the router. Plus, the location service can come-in really handy when coupled with the router to perform certain operations.
In order to have access to the location service, import it with LocationStrategy and PathLocationStrategy from @angular/common, add the members to your list of providers and inject Location in the constructor:
// ...
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
@Component({
...
providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]
})
export class AppComponent {
constructor(private location: Location) { }
// ...
}
Let’s say that we want methods to go forward or back in the navigation:
goBack() {
this.location.back();
}
goForward() {
this.location.forward();
}
You can get the current path with the Location.path method:
getPath() {
console.log(this.location.path());
}
The Angular router has an events method that returns an observable that we can subscribe to in order to listen for changes in the navigation. Let’s say that we want to listen to changes in the url and set an isRoot member variable to true if the user in at the root path:
isRoot: boolean;
ngOnInit() {
this.router.events.subscribe(event => {
if (this.location.path() !== '') {
this.isRoot = false;
} else {
this.isRoot = true;
}
});
}
With the above example, don’t forget to import and inject the Router from @angular/router.
The location service has a few more useful methods. Note that for all these methods the given URL is first normalized against the application’s base href value:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!