📅  最后修改于: 2023-12-03 15:13:24.443000             🧑  作者: Mango
AngularJS is a popular JavaScript framework for building dynamic web applications. One of its core features is the ability to make AJAX (Asynchronous JavaScript and XML) requests to retrieve data from a server without requiring a full page reload. In this guide, we'll explore how to use AngularJS's built-in methods for making AJAX requests and handling responses.
AngularJS provides two main methods for making AJAX requests: $http
and ngResource
. Both methods are built on top of JavaScript's XMLHttpRequest
object, but they offer different levels of abstraction and flexibility.
The $http
service is built into AngularJS and provides a simple way to make AJAX requests. Here's an example of how to use it:
$http({
method: 'GET',
url: '/api/users'
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log('Error:', response.status, response.statusText);
});
In this example, we're making a GET
request to the /api/users
endpoint. The then
method takes two callbacks: one for success and one for error. The success callback will be called if the request is successful and the error callback will be called if there's an error.
The ngResource
module provides a higher-level abstraction for working with RESTful APIs. It allows you to define a resource object that maps to a URL and provides methods for interacting with that resource. Here's an example:
angular.module('myApp').factory('User', ['$resource', function($resource) {
return $resource('/api/users/:id', { id: '@id' });
}]);
// Usage:
User.query(function(users) {
console.log(users);
});
User.get({ id: 123 }, function(user) {
console.log(user);
});
In this example, we're defining a User
resource that maps to the /api/users/:id
endpoint. The query
method retrieves a list of all users and the get
method retrieves a single user by ID.
Once you've made an AJAX request, you'll need to handle the response. AngularJS provides several methods for working with AJAX responses:
Both $http
and ngResource
return promises, which allow you to handle the response asynchronously. Here's an example:
$http({
method: 'GET',
url: '/api/users'
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log('Error:', response.status, response.statusText);
});
In this example, we're using the then
method to handle the response. The successCallback
function will be called if the request is successful and the errorCallback
function will be called if there's an error.
Interceptors allow you to intercept and manipulate HTTP requests and responses. You can use interceptors to add headers, modify the response, or handle errors. Here's an example:
angular.module('myApp').factory('authInterceptor', ['$injector', function($injector) {
var authInterceptor = {
request: function(config) {
var authService = $injector.get('AuthService');
if (authService.isAuthenticated()) {
config.headers['Authorization'] = 'Bearer ' + authService.getAccessToken();
}
return config;
},
responseError: function(response) {
if (response.status === 401) {
var authService = $injector.get('AuthService');
authService.logout();
}
return response;
}
};
return authInterceptor;
}]);
$httpProvider.interceptors.push('authInterceptor');
In this example, we're defining an authInterceptor
factory that adds an Authorization
header to every request if the user is authenticated. We're also defining a responseError
function that logs the user out if the server returns a 401 unauthorized error.
AngularJS's built-in support for AJAX requests makes it easy to build dynamic web applications that communicate with a backend server. Whether you're using $http
or ngResource
, handling responses asynchronously using promises and interceptors is a powerful way to handle errors and manipulate data.