![](/img/trans.png)
[英]$http.get request with multiple $http.get requests inside it not running properly
[英]Create a $http.get properly
我想正确地创建$ http.get服务,但是在AngularJS中遇到服务问题。 我创建了这段代码,它可以工作,但是所有代码都在控制器中:
var monApp = angular.module('monApp', []);
monApp .controller('PhoneListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('http://port:serveur/fichier.xml').then(function(response) {
var x2jObj = X2J.parseXml(response.data); //X2J.parseXml(xmlDocument, '/');
var tableauJSON = X2J.getJson(x2jObj);
}, function(a, b, c) {
alert("Impossible de télécharger le fichier");
});
}
]);
您能帮我在服务中创建它吗? 谢谢。
创建一个名称为fichierService
的服务和一个类似getData
的函数
monApp.factory("fichierService", function($http) {
return {
getData: function() {
return $http.get('http://port:serveur/fichier.xml');
}
}
});
并通过注入在PhoneListCtrl
控制器中使用该fichierService
服务
monApp .controller('PhoneListCtrl', ['$scope', '$http','fichierService',
function($scope, $http, fichierService) {
fichierService.getData().then(function(response) {
// rest of code
}, function(a, b, c) {
alert("Impossible de télécharger le fichier");
});
}
]);
monApp.service('myFooService', function() {
this.get = function (url) {
return $http.get(url).then(function(response) {
var x2jObj = X2J.parseXml(response.data);
var tableauJSON = X2J.getJson(x2jObj);
});
}
});
然后您可以像这样使用您的服务
monApp.controller('fooCtrl', function($scope, myFooService) {
myFooService.get('http://foo.com/foo.xml');
});
这应该为如何开始实施自己的服务提供一个思路。
这是完美的解决方案,控制者:
var app = angular.module("myApp", []);
app.controller("MainCtrl", ["$scope", "userService",
function($scope, userService) {
userService.getData();
}
]);
网络服务:
app.service("userService",["$http",
function($http) {
_this = this;
this.getData = function() {
$http.defaults.headers.common = {"Access-Control-Request-Headers": "accept, origin, authorization"};
$http.defaults.headers.common['Authorization'] = 'Basic ' + window.btoa('username' + ':' + 'password');
$http.get('http://YourServer:YourPort/rest/api/2/auditing/record').
success(function(data) {
console.log(data);
});
}
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.