【问题标题】:How to stop browser loading localStorage Item when it's not available in AngularJS如何在AngularJS中不可用时停止浏览器加载localStorage Item
【发布时间】:2017-02-11 12:02:49
【问题描述】:

假设我有一个导航栏,它在登录后显示个人资料图片。 我正在使用 Auth0 的锁,它在 localStorage 中设置用户配置文件。 img-src 来自 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);

当用户进入主页时,浏览器一直在寻找 lgin.profile.picture (不可用,因为他们还没有登录),所以微调器永远不会停止,除非登录。 如何纠正这个问题?

【问题讨论】:

  • 这不行吗? if(angular.isDefined(accessData)) { // your code }

标签: angularjs local-storage auth0


【解决方案1】:

使用简单的条件。如果键不存在,getItem() 将返回 null

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

【讨论】:

  • 请注意,您应该始终使用ng-src 以避免浏览器对图像提出错误请求。真的不确定你在说什么微调器。创建一个重现问题的演示
  • ng-src 确实纠正了这个问题。非常感谢。
猜你喜欢
  • 2012-03-22
  • 2015-10-31
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多