What is the best way to get json data using Angular

I have data that I was stripping exactly like the 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 I also have data in separate json files for each id. And the data will be persistent for most of the time. But they turn to him very often.

I know how to write code for accessing data in both the indicated ways. But I am confused as to how it would be better and faster to access the data.

+3


source to share


1 answer


One way you could approach this is by injecting a service into your controllers, which will have a function to return a promise for that data. This is beneficial because you will be able to implement and reuse this "wide application" service, and you can cache the response for performance as well. Here's an 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 only thing to consider if it is a call .then

, as it does when called asynchronously.




Another way you can do this, and it makes some assumptions here, might involve the following scenario: suppose this "persistent" data is something like some configuration data and you want to take advantage of this without allowing asynchronous promises in your controllers later. You can manually download the app after you initially get this data, offering the convenience of knowing that you will have this data in front.

To do this, create an AngularJS constant calleddata

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 that this is simplified, at least at our controller level. We just inject data

as a dependency that has already resolved us $http.get()

for us.

Plunker Link - demo constants

+2


source







All Articles