SoFunction
Updated on 2025-04-04

angularjs implementation interacts with server sharing

Real applications need to interact with real servers, mobile applications and emerging Chrome desktop applications may be an exception, but for all other applications, whether you want to persist data to the cloud or interact with other users in real time, you need to interact with the server.

To achieve this, Angular provides a service called $http. It provides an extensible list of abstract methods to make interaction with the server easier. It supports HTTP, JSONP and CORS methods. It also includes security support to avoid vulnerability in JSON format and XSRF. It allows you to easily convert request and response data, and even implements simple caching.

For example, we intend to have shopping sites get product information from servers instead of falsified data from memory. How to write server code is beyond the scope of this book, so let's just imagine that, for example, we have created a server that returns a product list in JSON format when querying the /products path.

The returned response example is as follows:

[

 {

  "id": 0,

  "title": "Paint pots",

  "description": "Pots full of paint",

  "price": 3.95

 },

 {

  "id": 1,

  "title": "Polka dots",

  "description": "Dots with that polka groove",

  "price": 12.95

 },

 {

  "id": 2,

  "title": "Pebbles",

  "description": "Just little rocks, really",

  "price": 6.95

 }

 ...etc...

]

We can write query code like this:

function ShoppingController($scope, $http) {

 $('/products').success(function(data, status, headers, config) {

  $ = data;

 });

}

Then use it like this in the template:

<body ng-controller="ShoppingController">

  <h1>Shop!</h1>

  <table>

   <tr ng-repeat="item in items">

    <td>{{}}</td>

    <td>{{}}</td>

    <td>{{ | currency}}</td>

   </tr>

  </table>

 </div>

</body>

As we said before, in the long run, it is beneficial for us to let the service proxy interact with the server, and this service can be shared by multiple controllers.