我正在尝试使用WebAPI调用和AngularJS构建一个简单的MVC WebApp。前端有一个md按钮,在控制器中定义了ng-click方法。每当我填满字段并单击按钮时,它应该转到angular Controller => factory =>调用Web Api并返回结果。但是,第一次单击后,什么也不会返回,但是如果我第二次单击同一按钮,它将获得我的数据。我不明白为什么会这样?
Index.cshtml
<md-button ng-click="GetResponse()" class="md-raised md-primary">
Get Response
</md-button>
Controller.js
$scope.GetResponse = function () {
debugger;
//Hardcodes the values, but still does not work
$scope.edm.shortDescription = 'SDesc';
$scope.edm.detailDescription = 'DDesc';
$scope.edm.changeType = $("#ddlChangeType")[0].innerText;
$scope.edm.category = 'CategoryName';
$scope.edm.application = 'AppName';
PrepareRequestService.GetFullRequest($scope.edm).then(function (d) {
$scope.fullRequest = d.data;
}, function (e) {
alert('Failed');
});
console.log(JSON.stringify($scope.fullRequest));
//This is the line I am getting null first and then value after second click.
}
Service.js
myAppModule.factory('PrepareRequestService', function ($http) {
var fac = {};
fac.GetFullRequest = function (edm) {
debugger;
//Here the Api Url is constructing properly
console.log('http://localhost:17669/api/PrepareRequest/' + edm.shortDescription + '/'
+ edm.detailDescription + '/'
+ edm.changeType + '/'
+ edm.category + '/'
+ edm.application + '/');
//This is the actual call to API
return $http.get('http://localhost:17669/api/PrepareRequest/' + edm.shortDescription + '/'
+ edm.detailDescription + '/'
+ edm.changeType + '/'
+ edm.category + '/'
+ edm.application + '/');
};
return fac;
});
Web API:
// GET: api/PrepareRequest/sDescription/dDescription/changeType/category/application
public RootObject Get(string sDescription, string dDescription, string changeType, string category, string application)
{
RequestBuilder p = new RequestBuilder();
RootObject ro = new RootObject();
ro = p.PopulatePPMParameter(application, sDescription, "Today", "myName", changeType, category);
return ro;
}
///在浏览器中尝试时,此API返回了我第二次单击GetResponse后得到的确切JSON格式数据。但是我需要在每次点击中都做到这一点。