<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://code.angularjs.org/1.3.0-beta.5/angular.js" data-semver="1.3.0-beta.5" data-require="angular.js@1.3.0-beta.5"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MyCtrl">
<h1>Car is</h1>
<p> {{ car.toString() }} </p>
</body>
</html>
angular.module("myApp", ['controllers', 'services']);
// ---------------------------- controllers ------------------------------------
angular.module('controllers', [])
.controller('MyCtrl', function($scope, HttpCarService) {
var successCallback = function(data, status, headers, config) {
$scope.car = data;
};
var errorCallback = function(data, status, headers, config) {
$scope.data = "there was an error";
};
HttpCarService.getCar()
.success(successCallback)
.error(errorCallback);
});
// ------------------------------ services -------------------------------------
angular.module('services', [])
.factory('HttpCarService', function($http) {
return {
/**
* This method will return an instance of Car (that is, this will deserialize
* the returned JSON into a Car object).
*/
getCar: function() {
return $http.get('car.json', {
method: 'GET',
transformResponse: function(data, headers) {
var c = angular.fromJson(data);
return new Car(c);
}
});
}
}
});
// ----------------------------- domain layer ----------------------------------
function Car(car) {
this.make = car.make;
this.model = car.model;
this.year = car.year;
this.torque = car.torque;
}
Car.prototype.toString = function() {
return this.year + " " + this.make + " " +
this.model + " with " + this.torque + " torque";
};
/* Styles go here */
How to use $http transformResponse
==================================
Example of how to use $http `transformResponse` to deserialize data from an $http request.
Note that there are a few problems with transformResponse:
- `transformResponse` is run BEFORE $http interceptors, which makes it rather useless
if you're going to depend on $http intereceptors for authorization (for example, if
will use [angular-http-auth](https://github.com/witoldsz/angular-http-auth)
- The $http `transformResponse` works, but the $resource `transformResponse` does not.
{
"make": "Honda",
"model": "Civic",
"year": 2042,
"torque": "ungodly"
}