Christo S. Christov
Christo S. Christov

Reputation: 2309

LocalStorage is not defined in angular2 service

I'm building an angular2 app with .net core backend. I have an app guard that blocks user navigation if the user isn't authenticated to the '/app' route. If I navigate to the '/app' route through the router after the user logs in it works fine, but if I type '/app' in the address bar it tells me that localStorage is not defined.

Here's my auth guard:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url

        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
}

Upvotes: 0

Views: 343

Answers (1)

Christo S. Christov
Christo S. Christov

Reputation: 2309

I resolved this by adding isBrowser check before entering the method. Turns out the sample project I'm using pre rendered the html on the server.

Upvotes: 1

Related Questions