Search code examples
jsonangularjsangularjs-serviceangularjs-factory

AngularJS loading JSON from URL via REST


I am still a bit new about AngularJS and just came across the topics about service, provider, and factory.

I have still problem(s) on:

  • How to load JSON response from server via REST.
  • Place the loading code in either service, provider, factory in which suits it best.
  • Provide encapsulation feature (getters/setters) in which $scope could watch the changes if the load was successful or not.

Please comment for clarifications.


Solution

  • The RESTful functionality is provided by Angular in the ngResource module. It's better to use $http service for non restful resources

    var phonecatServices = angular.module('phonecatServices', ['ngResource']);
    
    phonecatServices.factory('Phone', ['$resource',
      function($resource){
        return $resource('phones/:phoneId.json', {}, {
          query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
        });
      }]);
    

    The $resource service makes it easy to create a RESTful client with just a few lines of code. This client can then be used in our application, instead of the lower-level $http service.

    Please check this link for additional details

    https://docs.angularjs.org/tutorial/step_11