Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS使用工厂/服务从后端检索数据_Angularjs - Fatal编程技术网

AngularJS使用工厂/服务从后端检索数据

AngularJS使用工厂/服务从后端检索数据,angularjs,Angularjs,我正在接近AngularJS,我想从数据库中获取数据。我成功地做到了这一点 angular.module("myApp") .controller("listaUtentiCtrl", function($scope, $http) { $http.get("backListaUtenti.php").success(function(data) { $scope.utenti=data } ) }); 但是我想使用工厂/服务来使用来自多个控制器的数据(但不工作) 我在哪里失败了?问题

我正在接近AngularJS,我想从数据库中获取数据。我成功地做到了这一点

angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, $http) {
    $http.get("backListaUtenti.php").success(function(data) { $scope.utenti=data } )
});
但是我想使用工厂/服务来使用来自多个控制器的数据(但不工作)


我在哪里失败了?

问题在于您的服务实现。以下是重构后的代码:

angular.module("myApp")
.factory("utentiService", function($http) { 
    return {
        getData: function () {
            return $http.get("backListaUtenti.php").then(function (response) {
               return response.data;
            });
        }
    };
});

angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
    var userId = $routeParams.userId;
    utentiService.getData().then(function(data) {
        $scope.utente = filterFilter(data, { id: userId })[0];
    });
});

angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
    utentiService.getData().then(function (data) {
        $scope.utenti = data;
    });
});
如果您的数据是静态的,您可以缓存请求并避免不必要的请求,例如:

$http.get("backListaUtenti.php", { cache: true }); 

这种行为不是我所期望的。似乎$http.get让我获得了整个页面,而不仅仅是json,所以当我列出数据和输出utente时,我得到了{“方法”:“get”,“transformRequest”:[null],“transformResponse”:[null],“url”:“backListaUtenti.php”,“headers”:{“Accept”:“application/json,text/plain,/”}[{“citta”:“Roma”,“cognome”:“Rossi”,“nome”:“安德里亚”,“id”:“1},{“citta”:“米兰诺”,“cognome”:“Verdi”,“nome”:“Marco”,“id”:2},{“citta”:“Napoli”,“cognome”:“Neri”,“nome”:“Giovanni”,“id”:3},{“citta”:“Palermo”,“cognome”:“Gialli”,“nome”:“Roberto”,“id”:4}200 OKHi Manuel,我已经编辑了代码,现在它应该只返回响应中的数据。我像这样处理数据“>Tnx,我很高兴我帮了忙。回答得好,帮了我,节省了我的时间。谢谢
$http.get("backListaUtenti.php", { cache: true });