AngularJS http request
HTTP Request
AngularJS covers HTTP request feature $http
This is remote http service with XMLHttpRequest.
The $http$http service is a function which takes a single argument and return Promise
- $http.get
- $http.head
- $http.post
- $http.put
- $http.delete
- $http.jsonp
- $http.patch
Simple Usage GET
$http.get('/hello').
then(function(response) {
}, function(response) {
});
Simple Usage POST
$http.post('/hello', {msg:'Hello Japan!'}).
then(function(response) {
}, function(response) {
});
response is Object.
Example
This is nodejs express example to use this.
app.js
var fs = require('fs');
var approot = require('app-root-path');
// Read and display json file
app.get('/:file.json', function(req, res, next) {
var file = approot + '/data/' + req.params.file + '.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
next(err);
}//console.log(data);
res.json(JSON.parse(data));
});
});
app.get('/httptest', function(req, res, next) {
res.render('http', { title: 'HttpTest' });
});
httptest.ejs
<!DOCTYPE html>
<html ng-app="httpApp">
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<link rel='stylesheet' href='/bower/bootstrap/dist/css/bootstrap.css' />
<script src="/bower/angular/angular.min.js"></script>
<script src="/javascripts/http.js"></script>
</head>
<body ng-controller="httpController">
<div class="container-fluid">
Search: <input ng-model="query"><br>
Sorted by:<br>
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
<ul class="names">
<li ng-repeat="person in people | filter:query | orderBy:orderProp">
{{person.name}}
<p>{{person.age}}</p>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
This has angular.js and angular management javascript http.js
people are from http.js controller
http.js
var httpApp = angular.module('httpApp', []);
httpApp.controller('httpController', function($scope, $http){
$http.get('name.json').success(function(data) {
$scope.people = data;
}, function(response){
// Error
});
$scope.orderProp = 'age';
});
