Making HTTP Requests with AngularJS and $http Service

angular-js

Making HTTP Requests with AngularJS and $http Service

Communicating with external servers is essential for modern web applications. In AngularJS, the $http service provides a straightforward way to make HTTP requests to interact with APIs and retrieve data from external sources. This tutorial will guide you through the basics of using the $http service to send GET, POST, PUT, and DELETE requests in AngularJS.

Table of Contents

What is the $http Service?

The $http service in AngularJS is a core Angular module used for making HTTP requests. It provides methods like get, post, put, and delete, which allow us to interact with backend APIs, retrieve data, submit forms, update resources, and delete data. This service returns a promise, making it easy to handle asynchronous operations.

Setting Up Your AngularJS App

To start using the $http service, you need to set up a basic AngularJS application. Create an app module and a controller that will manage your HTTP requests.


<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS HTTP Requests</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="HttpController">
    ...
</body>
</html>
    

Making a GET Request

A GET request is used to retrieve data from the server. With AngularJS, we can use the $http.get() method to fetch data. Here’s an example that fetches data from an API endpoint and displays it in the view.


angular.module('myApp', [])
.controller('HttpController', function($scope, $http) {
    $scope.getData = function() {
        $http.get('https://jsonplaceholder.typicode.com/posts')
        .then(function(response) {
            $scope.posts = response.data;
        }, function(error) {
            console.error("Error fetching data:", error);
        });
    };
});
    

HTML for Displaying GET Data


<button ng-click="getData()">Load Posts</button>
<ul>
    <li ng-repeat="post in posts">{{ post.title }}</li>
</ul>
    

In this example, we use ng-click to call the getData function, which fetches posts from an API and binds the data to $scope.posts.

Making a POST Request

A POST request is used to send data to the server, typically to create a new resource. Here’s how you can make a POST request using the $http.post() method.


$scope.createPost = function() {
    var newPost = { title: 'New Post', body: 'This is a new post' };
    $http.post('https://jsonplaceholder.typicode.com/posts', newPost)
    .then(function(response) {
        console.log("Post created:", response.data);
        $scope.posts.push(response.data);
    }, function(error) {
        console.error("Error creating post:", error);
    });
};
    

HTML for POST Request


<button ng-click="createPost()">Create Post</button>
    

This example creates a new post by sending data to the API endpoint. The new post is then added to the existing list of posts.

Making a PUT Request

A PUT request is used to update existing data on the server. Here’s how to make a PUT request to update a specific post:


$scope.updatePost = function(id) {
    var updatedPost = { title: 'Updated Post', body: 'This post has been updated' };
    $http.put('https://jsonplaceholder.typicode.com/posts/' + id, updatedPost)
    .then(function(response) {
        console.log("Post updated:", response.data);
    }, function(error) {
        console.error("Error updating post:", error);
    });
};
    

HTML for PUT Request


<button ng-click="updatePost(1)">Update Post</button>
    

This example sends a PUT request to update the post with ID 1. The updatedPost object contains the new title and body content for the post.

Making a DELETE Request

The DELETE request is used to delete data from the server. The following example demonstrates how to delete a specific post:


$scope.deletePost = function(id) {
    $http.delete('https://jsonplaceholder.typicode.com/posts/' + id)
    .then(function(response) {
        console.log("Post deleted:", response.data);
    }, function(error) {
        console.error("Error deleting post:", error);
    });
};
    

HTML for DELETE Request


<button ng-click="deletePost(1)">Delete Post</button>
    

This example deletes the post with ID 1 from the server. The server responds with the data of the deleted post, which can be used to update the view if needed.

Handling Errors

When making HTTP requests, handling errors is essential to provide feedback to the user. AngularJS allows you to use the second parameter of the then function to catch errors:


$http.get('https://jsonplaceholder.typicode.com/invalid-url')
.then(function(response) {
    console.log("Data fetched:", response.data);
}, function(error) {
    console.error("Error fetching data:", error);
    $scope.errorMessage = "Could not retrieve data from the server.";
});
    

In this example, if the GET request fails, the error handler sets an error message, which can be displayed in the UI.

Conclusion

The $http service in AngularJS is a powerful tool for making HTTP requests to interact with external APIs. By using methods like $http.get, $http.post, $http.put, and $http.delete, you can fetch, create, update, and delete data from a server. Understanding these concepts will allow you to build dynamic, data-driven AngularJS applications that communicate with backend services seamlessly.