【发布时间】:2019-10-10 11:09:03
【问题描述】:
我有简单的 Angularjs 1.7 应用程序。一切正常,我能够从 Web API 获取数据到 angularjs 服务。当我在 Angularjs 服务上进行调试时,我可以看到数据是通过 Web API 从数据库中获取的。所以我使用 angularjs 控制器中的服务将数据提取到范围对象中。但我不确定为什么没有在控制器范围对象中获取数据。有什么我缺少的东西来修复它。
Service.js
(function () {
var app = angular.module('myApp');
app.factory('websiteService', function ($http, $q) {
var factory = [];
var deferred = $q.defer();
var baseURI = 'http://localhost:59029/api';
factory.getAllStudents = function () {
$http({
method: 'GET',
url: baseURI + '/Website/GetAllStudents'
}).then(function (response) {
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
return factory;
});
})();
Controller.js
(function () {
var app = angular.module('myApp');
app.controller('websiteController', ['$scope', '$http', 'websiteService', '$filter',
function ($scope, $http, websiteService, $filter) {
$scope.TestWebsite = "TestWebsite";
console.log($scope.TestWebsite);
//GET Students
websiteService.getAllStudents()
.then(function (response) {
$scope.FetchedAllStudents = response;
// NOT ABLE TO FETCH THE DATA HERE
}, function (error) {
// error handling here
});
}
]);
})();
【问题讨论】:
-
延迟 API 已经过时了。您可以简单地让
getAllStudents()返回$http.get(baseURI + '/Website/GetAllStudents'),其结果是一个承诺,并避免解决和拒绝的麻烦。 -
所以在控制器
websiteService.getAllStudents()中表示这样的@ -
是的——无需更改您在控制器中处理服务调用的方式。虽然,即使有这种变化,我也看不出你为什么在
response参数中没有得到任何东西。
标签: javascript angularjs asp.net-web-api