Using Angular's Location Service

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.
✖ Clear

🕵 Search Results

🔎 Searching...