Promises

Experimenting with AngularJS.

by nickxbs

HTML

<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.6/angular.min.js"></script>
<div id="mainContainer" ng-app="angularTest" ng-controller="MainCtrl">
    <div style="display: flex; flex-direction: column;align-items:center">
        
        <span>{{myvalue}}</span>
    </div>
</div>

JavaScript

'use strict';
var app = angular.module('angularTest', []);

app.controller('MainCtrl', ['$scope', '$q', '$http', function($scope, $q, $http) {

var url= 'https://www.randomtext.me/api/';

//Before
function before(){
	return $http.get(url)
    .success(function(data) {
      $scope.myvalue = data.text_out;
    })
    .error(function(dataError){
    	$scope.error = dataError;
    });
 }

 //After 
 function after(){
 /*
 Il servizio $http dalla versione angular 1.7 invece di gestire sia la callback success/error che le Promise, ora 	ritrona solo una Promise con then/catch. Il codice che prima utilizzava la success(function(data, status,...){...}) ora va sempre sostituito con una then(function(response){...}) in cui l'ggetto response contiene la property data  dalla success
 */
	return $http.get(url)
    .then(function(response) {
      $scope.myvalue = response.data.text_out;
    })
    .catch(function(responseError){
    	$scope.error = responseError.data;
    }); 
 }

//before();
after();

}]);