Tutorial

Using Angular's Location Service

Published on April 21, 2017
Default avatar

By Alligator.io

Using Angular's Location Service

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.

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.

Using the Location Service

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) { }

  // ...
}

Going Back & Forward

Let’s say that we want methods to go forward or back in the navigation:

goBack() {
  this.location.back();
}

goForward() {
  this.location.forward();
}

Getting the Current Path

You can get the current path with the Location.path method:

getPath() {
  console.log(this.location.path());  
}

Location Service + Router

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:

  • go: Changes the given URL and adds it to the browser’s history.
  • replaceState: Changes to the given URL, and replace the topmost URL in the history. This makes it so that if the user goes back it won’t go back to the url that the user was on, but the one before.
  • isCurrentPathEqualTo: Compares two given path values to see if they are equal.
  • normalize: Takes a path and returns a normalized path.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


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!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel