正确创建 $http.get

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);
                });
            }
        }
    ]);