Mac L. Lak Mac L. Lak - 1 year ago 80
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.


<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">
<img src="{{lgin.profile.picture}}" alt="{{}}">
<span class="caret"></span></a>


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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download