Episode 17 of 25

JSON and $http

Learn how to fetch data from servers using the $http service.

The $http service lets you make HTTP requests to fetch data from APIs and servers.

Basic GET Request

app.controller('DataCtrl', function($scope, $http) {
    $http.get('data/users.json').then(function(response) {
        $scope.users = response.data;
    }, function(error) {
        console.log('Error:', error);
    });
});

JSON Data File

// data/users.json
[
    { "name": "Alice", "age": 25, "city": "London" },
    { "name": "Bob", "age": 30, "city": "Paris" },
    { "name": "Charlie", "age": 28, "city": "Berlin" }
]
<div ng-controller="DataCtrl">
    <div ng-repeat="user in users">
        <h3>{{ user.name }}</h3>
        <p>Age: {{ user.age }} | City: {{ user.city }}</p>
    </div>
</div>

POST Request

$scope.saveUser = function() {
    $http.post('/api/users', $scope.newUser).then(function(response) {
        console.log('User saved:', response.data);
        $scope.users.push(response.data);
    });
};

$http Shortcut Methods

$http.get(url)
$http.post(url, data)
$http.put(url, data)
$http.delete(url)
$http.patch(url, data)

Handling Loading States

app.controller('DataCtrl', function($scope, $http) {
    $scope.loading = true;

    $http.get('data/users.json').then(function(response) {
        $scope.users = response.data;
        $scope.loading = false;
    });
});
<p ng-show="loading">Loading...</p>
<div ng-hide="loading">
    <!-- display data -->
</div>