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

时间:2015-09-09 15:52:09

标签: angularjs

我正在接近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,$q) {
    var self = $q.defer();

    $http.get("backListaUtenti.php")
        .success(function(data){
            self.resolve(data);
        })
        .error(function(){
            alert("Error retrieving data!");
        })
    return self.promise;
});

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

angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
    $scope.utenti = utentiService.utenti;
});

我在哪里失败?

1 个答案:

答案 0 :(得分:2)

问题在于您的服务实施。这是您重构的代码:

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

如果您的数据是静态的,您可以缓存请求并避免不必要的请求,如下所示:

System.IO BLACKSTAR$ pwd
/Users/BLACKSTAR/dotnet/corefx/src/System.IO
sameer:System.IO BLACKSTAR$ tree
.
├── System.IO.sln
├── ref
│   ├── System.IO.Manual.cs
│   ├── System.IO.cs
│   ├── System.IO.csproj
│   ├── bin
│   │   └── Debug
│   │       └── dotnet
│   │           ├── ref.dll
│   │           └── ref.xml
│   ├── project.json
│   └── project.lock.json
├── src
│   ├── Resources
│   │   └── Strings.resx
│   ├── System
│   │   └── IO
│   │       └── InvalidDataException.cs
│   ├── System.IO.csproj
│   ├── project.json
│   └── project.lock.json
相关问题