Angularjs $ http.post到webapi中的问题 [英] issue in Angularjs $http.post to webapi
问题描述
我正在以下站点上阅读angularjs $ http.post 快捷方式 http://docs.angularjs.org/api/ng .$ http#methods_post
I am reading angularjs $http.post shortcut method on the following site http://docs.angularjs.org/api/ng.$http#methods_post
它接受以下3个参数.
post(url, data, config)
当前,我面临一个如何从我的视图传递数据的问题.这是我的视图代码,要求用户输入ID和ContactNumber.
Currently i am facing an issue how to pass data from my view. Here is my view code which ask user to enter ID and ContactNumber.
<div data-ng-controller="postreq">
<form>
RequestID:<input type="text" data-ng-model="request.Id"/>
ContactNo:<input type="text" data-ng-model="request.newcontact"/>
<button data-ng-click="add()">Add</button>
</form>
</div>
这是我在Angularjs控制器中尝试执行的操作,它不起作用..不知道如何获取输入的request.Id和request.newcontact值.
Here what i am trying in my Angularjs controller and it is not working .. no idea how to get the entered values of request.Id and request.newcontact.
function postreq($scope, $http) {
$scope.add = function ()
{
$http.post(
'/api/request',
JSON.stringify(**?????? here i am confused how to pass data**),
{
headers: {
'Content-Type': 'application/json'
}
}
).success(function (data) {
$scope.request= data;
});
}
推荐答案
$ http 在内部做一些事情,所以我们作为应用程序开发人员不必考虑它们.
$http does a few things internally so that we, as application developers, don't have to think about them.
- 是否需要JSON.stringify
- 添加适当的标题
- 允许在请求之前/之后进行拦截
- 处理响应的缓存(与您的问题无关,但很高兴知道)
因此,这意味着在使用 $ http
时,我们不需要显式地执行这些操作.您可以将代码更改为:
So, this means that when using $http
, we don't need to explicitly do these things. You can change your code to:
$http.post('/api/request', $scope.request);
这将实现您的问题所需的一切.顺便说一句,这将返回一个 promise
和 success
和 error
回调方法.这些可用于处理响应.
This will achieve a everything that your question requires. BTW, this will return a promise
with success
and error
callback methods. These can be used to handle the response.
这篇关于Angularjs $ http.post到webapi中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!