Real-world applications need to interact with real-world servers, mobile apps and emerging chrome desktop apps may be the exception, but for all of them, whether you want to persist data to the cloud or need to interact with other users in real-time, you need to have your app interact with the server.
To achieve this, angular provides a service called $http. It provides an extensible list of abstract methods, making it easier to interact with the server. It supports HTTP, JSONP, and cors modes. It also includes security support to avoid the fragility and xsrf of JSON formats. It allows you to easily convert request and response data, and even implement a simple cache.
For example, we're going to have the shopping site get the product information from the server, rather than get it from the memory fake data. How to write service-side code has gone beyond the scope of this book, so let's just imagine that we've created a server that returns a list of items in JSON format when querying the/products path.
An example of the response returned is as follows:
[
{
' id ': 0,
' title ': ' Paint Pots ",
" description ":" Pots full of paint ",
" price ": 3.95
},
{
ID: 1,
"title": "Polka dots",
" Description ":" Dots with this polka Groove ",
" price ": 12.95
},
{
& nbsp; "id": 2,
"title": "Pebbles",
"description": "Just little Rocks , really ",
" price ": 6.95
}
... etc ...
]
We can write query code like this:
function Shoppingcontroller ($scope, $http) {
$http. Get ('/products ') ). Success (function (data, status, headers, config) {
$scope. Items = data;
});
}
<body ng-controller=" Shoppingcontroller ";
<table>
<tr ng-repeat= "item In items "
<td>{{item.title}}</td>
<td>{{item.description}}</td>
<td>{{item.price | currency}}</td>
</tr>
</table>
</div>
</body>
As we have said earlier, in the long run, it is good for us to have the service agent interact with the server, which can be shared by multiple controllers.
A book from theangularjs development of next-generation Web applications
Online version in Https://github.com/edagarli/AngularJSWeb