如何在网络不可用时读取JSON对象?

时间:2014-12-23 04:04:09

标签: angularjs

我想在本地存储中保存json响应对象。如果网络不可用,我可以从本地存储中读取数据,否则从服务器读取数据。我没有在任何地方看到这种情况。
提前致谢。

JSON
[
 {
  “tid”:“3388”,
   “名字”:“Adagio Bar”,
   “category_name”:“娱乐/酒吧”,
 “甲板”:“太阳甲板16”
 },
 {
  “tid”:“3439”,
  “名称”:“波提切利餐厅”,
  “category_name”:“食物和餐饮”,
 “甲板”:“Fiesta Deck 6”
},
{
“tid”:“3399”,
“名字”:“Cafe Caribe”,
“category_name”:“食物和餐饮”,
“甲板”:“Lido Deck 15”
 },
 {
“tid”:“3377”,
“名称”:“中心法院”,
“category_name”:“Pools,Sports& Spa”,
“甲板”:“星甲板19”
}
 ]

控制器

'use strict';
var princess_at_sea = angular.module('princess_at_sea', [])
princess_at_sea.controller("locationList", function($scope, $http){
    $scope.locationList = null;
    $http.get("location.json")
        .success(function(data){
            $scope.locationList  = data;        
            var indexedloc = [];
            $scope.locationListToFilter = function(){
                indexedloc = [];
                return $scope.locationList; 
            }
            $scope.filterLocation = function(Loc){
                var locationIsNew = indexedloc.indexOf(Loc.category_name) == -1;
                if(locationIsNew){
                    indexedloc.push(Loc.category_name);                 
                }
                return locationIsNew;
            }   
            $scope.returnFilterLoc = function(){return indexedloc};
        })
        .error(function(data) {
            $("div.content").html("Error");
        });
});

HTML enter image description here

我也添加了一个网址 http://jsfiddle.net/s1812ap8/

1 个答案:

答案 0 :(得分:0)

您需要执行上面提到的Mason,但请注意0状态代码。

function error(response) {
    if (response.status === 0) {
       errorStatus = 'No connection. Verify application is running.';
    } else if (response.status == 401) {
       errorStatus = 'Unauthorized';
    } else if (response.status == 405) {
       errorStatus = 'HTTP verb not supported [405]';
    } else if (response.status == 500) {
       errorStatus = 'Internal Server Error [500].';
    } else {
      errorStatus = response.data;
    }
   }