我是角色的初学者,我希望在经过一些操作后检索网址(http://myurl.com)的http获取响应。
我测试了但没有结果:/
var app = angular.module('plunker', []);
app.factory('myService', function($http) {
return {
async: function() {
return $http.get('http://apibuilder-apidiscovery.kermit.rd.francetelecom.fr/infrastructures/16857');
}
};
});
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function(d) { //2. so you can use .then()
$scope.data = d;
});
});
HTML
<body>
<div ng-controller="MainCtrl">
Data: {{data}}<br>
</div>
</body>
非常感谢你。
答案 0 :(得分:1)
数据分配应为$scope.data = d.data;
<强>控制器强>
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function(d) { //2. so you can use .then()
$scope.data = d.data;
}, function(error){
console.log('Error occured');
});
});
注意还要确保如果您尝试拨打外部域名,则应启用
CORS
。此外,您可能需要在请求中传递autherization标头。
答案 1 :(得分:0)
的script.js
var app = angular.module('plunker', []);
app.factory('myService', function($http,$q) {
var myService = {
async : async,
};
return myService;
function async() {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://apibuilder-apidiscovery.kermit.rd.francetelecom.fr/infrastructures/16857',
headers: {
"Content-Type": "text/plain",
// you can add headers here
}
}).then(function(reply) {
d.resolve(reply.data);
}, function(error) {
d.reject(error.data);
});
return d.promise;
}
});
app.controller('MainCtrl', function(myService, $scope) {
myService.async()
.then(function(result) {
$scope.data = result;
});
});
和索引文件
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
Data: {{data}}<br>
</body>
</html>