Angular and RESTful Api HTTP access --- some options using $http or $resource

 

$http - used to create HTTP request info & process the returned response ---basically like AJAX

 

// Simple GET request example:
  $http({    method: 'GET',    url: '/someUrl'  }).then(function successCallback(response) { 
         // this callback will be called asynchronously
         // when the response is available
         }, function errorCallback(response) {
             // called asynchronously if an error occurs
            // or server returns response with an error status.
       });

SHORTCUT methods
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Complete list of shortcut methods:

Here is an example to request the file sample_json.js and it grabs the response and the data (response.data) and prints it out to console (in addition to setting the value of $scope.jsondata used somewhere in program)

$http.get('sample_json.js')
  		.then(function (response){
  			$scope.jsondata = response.data;    //special note in Angular JS  $scope is the application object, so this means we are making a variable jsondata
  			console.log("status:" + response.status);
  		}).catch(function(response) {
  		  console.error('Error occurred:', response.status, response.data);
  		}).finally(function() {
  			 console.log("Task Finished.");
  		});

 

sample_json.js

[  {  	"id" : "1",  	"name" : "Shankar",  	"location" : "Varanasi"  	},
  	{  	"id" : "2",  	"name" : "Ram",  	"location" : "Ayodhya"  	},
  	{  	"id" : "3",  	"name" : "Krishna",  	"location" : "Mathura"  	}
]  

 

call the above javascript from inside html

<html>
  <head>
     <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
     <script src="app.js"></script>   <----CALLING THE APP JAVASCRIPT ABOVE
  </head>


  <body>
  	<div ng-app="myApp" ng-controller="myController">
   	    <ul>
   		<li ng-repeat="row in jsondata">  <----remember the data returned from the javascript http request put the data in a scope variable = jsondata  
  		     {{ row.id + ', ' + row.name + ', ' + row.location}} <br>  <----we are cycling through the data row by row in the jsondata variable 
  	        </li>
  	    </ul>
  	</div>
  </body>
</html>   

results of loading the html

$resource - used to get server-side data sources using stictly REST (get, post, put, delete,..)

var resource = $resource(URL, parameters);

var resource2 = $resource(url, [paramDefaults], [actions], options);

Perform REST method on the resource:

resource.get(parameters, callback);
resource.save(parameters, callback);
(query, delete also methods)

 

example 1 - a simple get request with parameter userId =123

var User = $resource('/user/:userId', {userId:123});

var user = User.get({userId:123}, function() {
    user.abc = true;
    user.$save();
  });

example 2 - FIRT a request passing {userID:123, cardID:29930030006} with parameter = {charge:true}

AND POST to set the name to J. Smith AND POST to charge $9.99 to the card
AND POST to create a new card

var CreditCard =  $resource('/user/:userId/card/:cardId',
   {userId:123, cardId:29930030006}, {
    charge: {method:'POST', params:{charge:true}}
   });


// We can retrieve a collection from the server
  var cards = CreditCard.query(function() {
    // GET: /user/123/card
    // server returns: [ {id:456, number:'1234', name:'Smith'} ];
      var card = cards[0];
    // each item is an instance of CreditCard
    expect(card instanceof CreditCard).toEqual(true);
    card.name = "J. Smith";
    // non GET methods are mapped onto the instances
    card.$save();
    // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
    // server returns: {id:456, number:'1234', name: 'J. Smith'};
      // our custom method is mapped as well.
    card.$charge({amount:9.99});
    // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
  });


// we can create an instance as well
  var newCard = new CreditCard({number:'0123'});
  newCard.name = "Mike Smith";
  newCard.$save();
  // POST: /user/123/card {number:'0123', name:'Mike Smith'}
  // server returns: {id:789, number:'0123', name: 'Mike Smith'};
  expect(newCard.id).toEqual(789);

 

example 3 --simple get request with parameter of id=234

 var PhotoListOfUser = $resource('/photos/:id', {id:234}, {
   get: {method: 'get', isArray: true}   });

 PhotoListOfUser.get({id: userId}, function(userPhotos) {
   console.log('userPhotos', userPhotos);
   });  Generates a HTTP GET to the URL and returns the model (an array of Photos) 

 

 

example 4 - POST request to create a comment="New Comment!" on a photo with id=939

var AddComment = $resource('/commentsOfPhoto/:id', {id:939});

AddComment.save({commentText: 'New Comment!'}, function (comment) {
  console.log('Added comment', comment);
   });  Generates a HTTP POST (rest create) to the URL and the model created

 

 

 

 

© Lynne Grewe