[英]How to redirect from the service to the controller with the response data in angularjs?
[英]How to get data from Angularjs Service Response to Controller Scope Object
我有简单的 Angularjs 1.7 应用程序。 一切正常,我能够从 web API 到 angularjs 服务中获取数据。 当我在 Angularjs 服务上进行调试时,我可以看到正在通过 Web API 从数据库中获取数据。 所以我使用 angularjs controller 中的服务将数据提取到 scope ZA8CFDE63311C46EB2AC96F916 但我不确定为什么 controller scope object 中没有获取数据。 有什么我缺少的东西来修复它。
服务.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
});
}
]);
})();
无需使用$q.defer
制造 promise,因为 $http 服务已经返回 promise:
app.factory('websiteService', function ($http, $q) {
var factory = [];
̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var baseURI = 'http://localhost:59029/api';
factory.getAllStudents = function () {
return $http({
method: 'GET',
url: baseURI + '/Website/GetAllStudents'
}).then(function (response) {
return response.data;
});
}
return factory;
});
有关更多信息,请参阅这是“延迟反模式”吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.