我使用 AngularJS 来构建我的 Web 应用程序,我一直使用 Controller 来发出 HTTP 请求,这使事情对我来说变得更容易和清晰。
但是为了更好的代码结构以及应用程序的更好执行,我想使用服务而不是 Controller 来使用 Web 服务。
我尝试制作:
var app = angular.module('ofcservices', []);
app.factory('news', ['$http', function ($http) {
var news={};
news.getnews= function () {
return $http.get('http://int.footballclub.orange.com/ofc/news?offset=0&limit=5');
};
return news;
}]);
和 Controller 的代码:
.controller('news', function($scope, ofcservices) {
$scope.news = ofcservices.getnews();
})
一切似乎都是正确的?
最佳答案
ofcservices.getnews()
is a promise您需要使用成功和错误功能进行管理
ofcservices.getnews().
success(function(data) {
$scope.news=data
}).
error(function(data, status, headers, config) {
//show a error
});
将 app.factory('news'
更改为 app.factory('newsFactory'
) 并在 controller('news', function( $scope, newsFactory) {
您可以获得有关 promise in the angular documentation 的更多数据
关于javascript - 如何在 Angular JS 中使用带有 Http 请求的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30975249/