Mac L. Lak Mac L. Lak - 2 months ago 11
AngularJS Question

How to stop browser loading localStorage Item when it's not available in AngularJS

Suppose I have a navbar which show a profile picture after login.
I'm using Auth0's lock, which set user profile in localStorage. The img-src came from localStorage.

NavbarView.html

<li ng-if="!lgin.isAuthenticated"><a ng-click="lgin.authService.login()">Sign in</a></li>
<li ng-if="lgin.isAuthenticated" class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown">
<strong>{{lgin.profile.name}}</strong>
<img src="{{lgin.profile.picture}}" alt="{{lgin.profile.name}}">
<span class="caret"></span></a>


loginController.js

var lgin = this;
lgin.isAuthenticated = $rootScope.isAuthenticated;
var accessData = localStorage.getItem('profile');
lgin.profile = angular.fromJson(accessData);


When user enter the homepage, the browser keep finding for lgin.profile.picture (which is not available, because they didn't login yet), so the spinner never stop unless logging in.
How to correct this?

Answer

Use a simple conditional. If a key doesn't exist, getItem() will return null

var accessData = localStorage.getItem('profile');
if(accessData ){
   lgin.profile = angular.fromJson(accessData);
}