javascript - Which is the best way to retrieve json data using Angular -


i have data segregated json structure below

{     "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"             }         ]     } } 

but have data in separate json files each id. , data constant of time. going accessed frequently.

i know how write code access data in both mentioned ways. confused way better , faster access data.

one way approach inject service controllers have function return promise data. advantageous because you'll able inject , reuse service "app wide" , can cache response performance. here example implementation...

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 - demo

the thing mindful of if call .then since in asynchronous call.


another way can this, , making assumptions here, include following scenario: assume "constant" data configuration data , wish hands on without resolving asynchronous promises in controllers later on. manually bootstrap app after retrieving data, offering convenience of knowing you'll have data front.

to this, lets create angularjs constant called data

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) }]); 

you can see simplified, @ least @ our controller level. inject data dependency already has resolved our $http.get() us.

plunker link - demo - constants


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

php - Find a regex to take part of Email -

javascript - Function overwritting -