以下是一些常见的 $http 服务的用法:
1. 发送 GET 请求
app.controller('myController', function($scope, $http) {
$http.get('/api/data')
.then(function(response) {
// 请求成功的处理
$scope.data = response.data;
})
.catch(function(error) {
// 请求失败的处理
console.error('Error:', error);
});
});
2. 发送 POST 请求
app.controller('myController', function($http) {
var postData = { key: 'value' };
$http.post('/api/post', postData)
.then(function(response) {
// 请求成功的处理
console.log('Response:', response.data);
})
.catch(function(error) {
// 请求失败的处理
console.error('Error:', error);
});
});
3. 发送 PUT 请求
app.controller('myController', function($http) {
var putData = { key: 'new-value' };
$http.put('/api/put', putData)
.then(function(response) {
// 请求成功的处理
console.log('Response:', response.data);
})
.catch(function(error) {
// 请求失败的处理
console.error('Error:', error);
});
});
4. 发送 DELETE 请求
app.controller('myController', function($http) {
$http.delete('/api/delete')
.then(function(response) {
// 请求成功的处理
console.log('Response:', response.data);
})
.catch(function(error) {
// 请求失败的处理
console.error('Error:', error);
});
});
5. 配置请求
可以使用 config 对象来配置请求,例如设置请求头、超时等:
app.controller('myController', function($http) {
var config = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
timeout: 5000 // 请求超时时间为5秒
};
$http.get('/api/data', config)
.then(function(response) {
console.log('Response:', response.data);
})
.catch(function(error) {
console.error('Error:', error);
});
});
6. 使用 $http 的便捷方法
$http 还提供了一些便捷的方法,如 $http.get、$http.post、$http.put、$http.delete,它们可以简化代码:
app.controller('myController', function($http) {
$http.get('/api/data')
.then(function(response) {
console.log('Response:', response.data);
})
.catch(function(error) {
console.error('Error:', error);
});
});
这些便捷方法直接返回一个 Promise 对象,不再需要显式地调用 .then 和 .catch。
以上是一些基本的 $http 服务的用法。在实际应用中,你可能还会使用拦截器、设置请求配置、处理响应等高级功能。详细的 $http 服务用法可以查阅 AngularJS 官方文档。
转载请注明出处:http://www.pingtaimeng.com/article/detail/4861/Angular