Using the Location service with @angular/upgrade

I don’t know if there is already a post somewhere about this, but when I had this problem a few weeks ago (more like 2 months ago) I couldn’t find anything about how to use the Location service from Angular 2 online.

So, you might be in the same situation I am where you’re migrating an Angular 1 web application to Angular 2 (I’m going to start calling Angular 1 NG1 and Angular 2 NG2 because… laziness), which means running both frameworks side by side. If your situation is similar to mine, you may be running NG2 components in your NG1 app and still using NG1’s router.

That’s cool and all, but now you may want to navigate to another route from within your NG2 controller. You could upgrade the $location service and use that, and that would probably be fine but, like me, you probably want to use NG2 services as much as possible so here’s how you setup the Location service in NG2. It’s actually quite simple.

When I tried it for the first time I thought I just had to import the CommonModule from @angular/common. WRONG! No, the Location service is not referenced in the CommonModule. Instead you have to add the Location service directly to the providers in your module, but that’s not the only thing, you also have to set a LocationStrategy otherwise NG2 will start to complain.

So, this is how you do it, I have a shared module called shared.module.ts (DUH!), it looks kinda like this:

import { Location, LocationStrategy, HashLocationStrategy } from '@angular/common';

    // It has WAY more stuff than this IRL.
    providers: {
        { provide: LocationStrategy, useClass: HashLocationStrategy }
export class SharedModule {

Simple like that! Now, you can just inject Location in your components or services like this:

@Component({ /*...*/ })
export class MyComponent {
    constructor(location: Location) {

        // you can also get the current location by:
        let path = location.path();

Now, as you can see, I’m using a HashLocationStrategy. The reason I’m using that, as you might have already figured out, is that my routes use the octothorpe (yeah, that’t the name of the symbol, but you can say hash, hashtag, IRC Channel, or whatever) like http://whatever/#/myroute. If that’s not your case and you don’t have the # in your urls, then you can use the PathLocationStrategy instead.

And that’s basically it. This was a simple post mostly to remind myself of this in the future, but it may be useful for someone else.

I’m still going to write the Aurelia + Typescript post, I’ve just been lazy… err… I mean, busy lately. Until then, have a good one!

Eric Mackrodt on sabyoutubeEric Mackrodt on sabtwitterEric Mackrodt on sablinkedinEric Mackrodt on sabgithubEric Mackrodt on sabemail
Eric Mackrodt
Software Developer, Tech Enthusiast, Music Lover, Movie Watcher, TV Junkie, food eater, air breather...
Back To Top