我是一个初学者,我想在一些操作后检索url (http://myurl.com)的http get响应。
我测试了,但是没有结果:/
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>
数据赋值应为$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
。此外,您可能需要在请求中传递授权头。
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>