AngularJS AJAX - $ http


$http è un servizio AngularJS per la lettura di dati da server remoti.


AngularJS $http

Il servizio AngularJS $httpeffettua una richiesta al server e restituisce una risposta.

Esempio

Fai una semplice richiesta al server e mostra il risultato in un'intestazione:

<div ng-app="myApp" ng-controller="myCtrl">

<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("welcome.htm")
  .then(function(response) {
    $scope.myWelcome = response.data;
  });
});
</script>

Metodi

L'esempio sopra utilizza il .getmetodo del $http servizio.

Il metodo .get è un metodo di scelta rapida del servizio $http. Esistono diversi metodi di scelta rapida:

  • .delete()
  • .get()
  • .head()
  • .jsonp()
  • .patch()
  • .post()
  • .put()

I metodi sopra sono tutti scorciatoie per chiamare il servizio $http:

Esempio

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
      url : "welcome.htm"
  }).then(function mySuccess(response) {
    $scope.myWelcome = response.data;
  }, function myError(response) {
    $scope.myWelcome = response.statusText;
  });
});

L'esempio sopra esegue il servizio $http con un oggetto come argomento. L'oggetto specifica il metodo HTTP, l'URL, cosa fare in caso di successo e cosa fare in caso di errore.



Proprietà

La risposta dal server è un oggetto con queste proprietà:

  • .configl'oggetto utilizzato per generare la richiesta.
  • .datauna stringa, o un oggetto, che trasporta la risposta dal server.
  • .headersuna funzione da utilizzare per ottenere informazioni sull'intestazione.
  • .statusun numero che definisce lo stato HTTP.
  • .statusTextuna stringa che definisce lo stato HTTP.

Esempio

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("welcome.htm")
  .then(function(response) {
    $scope.content = response.data;
    $scope.statuscode = response.status;
    $scope.statustext = response.statusText;
  });
});

Per gestire gli errori, aggiungi un'altra funzione al .thenmetodo:

Esempio

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("wrongfilename.htm")
  .then(function(response) {
    // First function handles success
    $scope.content = response.data;
  }, function(response) {
    // Second function handles error
    $scope.content = "Something went wrong";
  });
});

JSON

I dati che ottieni dalla risposta dovrebbero essere in formato JSON.

JSON è un ottimo modo per trasportare i dati ed è facile da usare all'interno di AngularJS o di qualsiasi altro JavaScript.

Esempio: sul server abbiamo un file che restituisce un oggetto JSON contenente 15 clienti, tutti racchiusi in un array chiamato records.

Fare clic qui per dare un'occhiata all'oggetto JSON.

×

clienti.php

"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body><p>{\n\"records\":[\n{\"Name\":\"Alfreds Futterkiste\",\"City\":\"Berlin\",\"Country\":\"Germany\"},\n{\"Name\":\"Ana Trujillo Emparedados y helados\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Antonio Moreno Taquería\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Around the Horn\",\"City\":\"London\",\"Country\":\"UK\"},\n{\"Name\":\"B's Beverages\",\"City\":\"London\",\"Country\":\"UK\"},\n{\"Name\":\"Berglunds snabbköp\",\"City\":\"Luleå\",\"Country\":\"Sweden\"},\n{\"Name\":\"Blauer See Delikatessen\",\"City\":\"Mannheim\",\"Country\":\"Germany\"},\n{\"Name\":\"Blondel père et fils\",\"City\":\"Strasbourg\",\"Country\":\"France\"},\n{\"Name\":\"Bólido Comidas preparadas\",\"City\":\"Madrid\",\"Country\":\"Spain\"},\n{\"Name\":\"Bon app'\",\"City\":\"Marseille\",\"Country\":\"France\"},\n{\"Name\":\"Bottom-Dollar Marketse\",\"City\":\"Tsawassen\",\"Country\":\"Canada\"},\n{\"Name\":\"Cactus Comidas para llevar\",\"City\":\"Buenos Aires\",\"Country\":\"Argentina\"},\n{\"Name\":\"Centro comercial Moctezuma\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Chop-suey Chinese\",\"City\":\"Bern\",\"Country\":\"Switzerland\"},\n{\"Name\":\"Comércio Mineiro\",\"City\":\"São Paulo\",\"Country\":\"Brazil\"}\n]\n} </p></body></html>\n<script>\n    function gtElInit() {\n        var lib = new google.translate.TranslateService();\n        lib.translatePage('', 'it', function() {});\n    }\n</script>\n<script src=\"https://translate.google.com/translate_a/element.js?cb=gtElInit&amp;client=wt&amp;hl=it&amp;te=pod\" type=\"text/javascript\"></script>\n\n\n</html>"

Esempio

La ng-repeatdirettiva è perfetta per scorrere un array:

<div ng-app="myApp" ng-controller="customersCtrl">

<ul>
  <li ng-repeat="x in myData">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("customers.php").then(function(response) {
    $scope.myData = response.data.records;
  });
});
</script>

Applicazione spiegata:

L'applicazione definisce il customersCtrlcontroller, con a $scopee $httpoggetto.

$httpè un oggetto XMLHttpRequest per la richiesta di dati esterni.

$http.get()legge i dati JSON da https://www.w3schools.com/angular/customers.php .

In caso di successo, il controller crea una proprietà, myData, nell'ambito, con dati JSON dal server.