【问题标题】:Create a $http.get properly正确创建 $http.get
【发布时间】:2016-04-14 19:37:19
【问题描述】:

我想正确地创建一个 $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");
        });
    }
]);

你能帮我在服务中创建它吗? 谢谢。

【问题讨论】:

标签: javascript angularjs angularjs-service http-get


【解决方案1】:

创建一个名称为fichierService 的服务和一个函数getData like

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

【讨论】:

    【解决方案2】:
    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');
    });
    

    这应该可以让您了解如何开始实施您自己的服务。

    【讨论】:

    • monApp.fooService 是否正确?应该是 monApp.service
    【解决方案3】:

    这是完美的解决方案,控制器:

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

    【讨论】:

      猜你喜欢
      • 2017-12-04
      • 2016-04-02
      • 1970-01-01
      • 2011-03-02
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多