2015-06-14 31 views
3

我有我分開,就像下面這是使用檢索JSON數據的最佳方式角

{ 
    "Id": { 
     "1": [ 
      { 
       "Item1": "Item One", 
       "Item2": "Item Two", 
       "Item3": "Item Three" 
      } 
     ], 
     "2": [ 
      { 
       "Item1": "Item One", 
       "Item2": "Item Two", 
       "Item3": "Item Three" 
      } 
     ], 
     "3": [ 
      { 
       "Item1": "Item One", 
       "Item2": "Item Two", 
       "Item3": "Item Three" 
      } 
     ] 
    } 
} 

的JSON結構數據,但我也有在每個ID單獨的JSON文件中的數據。而且大部分時間數據都將保持不變。但它會頻繁訪問。

我知道如何編寫代碼以上述方式訪問數據。但是我感到困惑的是訪問數據的方式會更好,更快。

+0

進行快速訪問 - 使用本地存儲 – nikhil

+1

從文件中獲取你的數據只有一次,並通過使用服務維護它的程序。這是你可以採取的最好的方法。 – simon

+0

謝謝@simon。我瞭解了這些服務,他們非常有用。 –

回答

2

你可以採取的一種方法是向服務器注入一個服務器,該服務器將有一個函數返回這個數據的承諾。這是有利的,因爲您可以在「應用程序範圍內」注入並重新使用此服務,並且還可以緩存性能響應。下面是一個例子實施...

var app = angular.module('app', []); 

app.service('DataService', ['$http', function ($http) { 
    this.getData = function(){ 
     return $http.get('data.json', { cache: true }) 
    } 
}]); 

app.controller('ctrl', ['$scope', 'DataService', function($scope, DataService) { 
    DataService.getData().then(function(response) { 
     console.log(response.data); 
    }); 
}]); 

Plunker Link - 演示

要留神,如果是一個異步調用,因爲此調用.then的唯一的事。


另一種方法可以做到這一點,這是在這裏做一些假設,可能包括以下情形:假設這個「不變」的數據是像一些配置數據,並希望得到你的手在這個無稍後解決控制器中的異步承諾。您可以在最初檢索這些數據後手動引導您的應用程序,並提供便利知道您將預先獲得此數據。

要做到這一點,讓我們創建一個名爲AngularJS constantdata

var app = angular.module('app', []); 

(function() { 
    var initInjector = angular.injector(['ng']); 
    var $http = initInjector.get('$http'); 
    $http.get('data.json').then(
    function (response) { 

     app.constant('data', response.data); 

     angular.element(document).ready(function() { 
      angular.bootstrap(document, ['app']); 
     }); 
    } 
); 
}()); 

app.controller('ctrl', ['$scope', 'data', function($scope, data) { 
    console.log(data) 
}]); 

你可以看到這個被簡化,至少在我們的控制水平。我們只是注入data作爲依賴關係,其中已經已經爲我們解決了我們的$http.get()

Plunker Link - 演示 - 常數

+0

非常有用。非常感謝你。 –

相關問題