AngularJS

$http, services

Agenda

1. $http, $q

2. services

3. Feature structure

 

22

$http service

• The $http service is simply a wrapper around the browser’s raw XMLHttpRequest object

• Pass it a configuration object

• Returns a promise with:

–then

–catch

–finally

–success (depricated 1.4.4)

–error (depricated 1.4.4)

$http example (depricated)

$http({
	method: “GET”,
	url: “/api/users”,
})
.success( (data, status, headers, config)) => {
	// This is called when 
	// the response is ready
}
.error( (data, status, header, config) => {
	// This is called when 
	// the response comes back with an error status
});

$http example (now)

$http({
    method: “GET”,
    url: “/api/users”
})
.then(successCallback)
.catch(errorCallback);

function successCallback(responseObject) {
    return responseObject.data;
}
function errorCallback(responseObject) {
    return $q.reject(`Error: ${responseObject.status}`);
}

$http Shortcut Methods

$http.get(url [, optConfigObj]);
$http.delete(url [, optConfigObj]);
$http.head(url [, optConfigObj]);
$http.jsonp(url [, optConfigObj]); // JSON_CALLBACK

$http.post(url, data [, optConfigObj]);
$http.put(url, data [, optConfigObj]);
$http.patch(url, data [, optConfigObj]);

//Examples
$http.get(“/api/user.json”);
$http.jsonp(“/api/users.json?callback=JSON_CALLBACK”);

$http Configuration Object

// Main options

method 
url
params
data
headers
cache

Why use Promises?

$q service

$q service

// some service
var deferred = $q.defer();
if (success) {
  deferred.notify(notification); // for long processes
  deferred.resolve(resolveData);
}
else {
  deferred.reject(rejection);
}

return deferred.promise;

$q Constructor (ES6)

let promise = $q( function(resolve, reject) {
  if (success) {
    resolve(resolveData);	  
  }
  else {
    reject(rejection);
  }	
	
});

return promise;

Services

class AdminProfileAPIService {
  constructor($http) {
    this.$http = $http;
  }

  getDriverInfo(driverAdminId) {
    return this.$http({
      method: 'get',
      url: 'localhost:3000/admin-info'
    })
      .then(this.successAdminSettings.bind(this));
  }

  successAdminSettings(response) {
    return response.data.data;
  }
}

AdminProfileAPIService.$inject = [
  '$http'
];

export default AdminProfileAPIService;

Feature structure

app/
----assets/
--------fonts/
--------images/             // main style 
----core/
--------core.module.js
----features/
--------features.module.js
----shared/
--------shared.module.js
----styles/
app.constants.js
app.controller.js
app.module.js
app.route.js
app.run.js

AngularJS

By Oleg Rovenskyi

AngularJS

$http, services

  • 298