2017-04-12 47 views
1

我正在開發一個Angular應用程序。我需要在SQLite中創建一個數據庫,以便在我的Android項目中使用本地數據庫。我看到的每一個教程都教會我在工廠製作並在其他頁面中調用它。無法處理控制器中的工廠信息

問題是,在很多情況下,我需要獲取這些信息並對其進行處理。我已經能夠在表單中顯示它,但不幸的是,我無法操縱工廠返回的對象。

我的代碼如下。

廠源碼:

var db = null; 
var clienteselec = []; 
var sqlite = angular.module('sqlite', ['ionic', 'ngCordova']); 

sqlite.run(function ($ionicPlatform, $cordovaSQLite, $window) { 
    $ionicPlatform.ready(function() { 
     db = $cordovaSQLite.openDB({ name: "rollers.db", location: 1 }); 

     $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS clientes (id integer primary key, nome varchar(40))"); 
     $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS instalacao (id integer primary key, idCliente int, dataInst datetime)"); 
     $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS manutencao (id integer primary key, idCliente int, idInstalacao int, dataManut datetime)"); 
     $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS equipamento (id integer primary key, idInstalacao int, idManutencao int, TC int autoincrement, posicao varcar(1), Rolo varchar(40), dataEquip datetime)"); 
    }); 
}) 

sqlite.factory('clientesFactory', function ($cordovaSQLite, $rootScope) { 
    return { 
insert: function (Nome) { 
      var query = "INSERT INTO clientes (nome) VALUES (?);"; 
      var values = [Nome]; 

      $cordovaSQLite.execute(db, query, values).then(
       function (res) { 
        alert('Cliente Cadastro com Sucesso!'); 

        $cordovaSQLite.execute(db, "SELECT max(id) as id from clientes", []).then(
         function (res) { 
          if (res.rows.length > 0) { 
           var valores = res.rows.item(0); 
           $rootScope.idCliente = valores.id; 
          } 
         } 
       ); 
       }, 
       function (err) { 
        alert('Cliente não cadastrado. Estamos verificando o problema!'); 
       } 
      ); 
     }, 

     selectTodos: function(tab){ 
      var query = "SELECT * FROM " + tab; 

      clienteselec = []; 
      $cordovaSQLite.execute(db, query,[]).then(function (result) { 
       if(result.rows.length){ 
        for (var i = 0; i < result.rows.length; i++) { 
         clienteselec.push(result.rows.item(i)); 
        } 
       }else{ 
        console.log("no data found!"); 
       } 
      }, function(err){ 
       console.log("error" + err); 
      }); 
     }, 
}); 

控制器:

.controller('ClienteCtrl', ['clientesFactory', '$scope', '$state', '$window', '$rootScope', function (clientesFactory, $scope, $state, $window, $rootScope) { 
    $scope.listaClientes = function() { 
     clientesFactory.insert('teste'); 
     clientesFactory.selectTodos('clientes'); 
     $scope.seleciona = clienteselec; 
    } 
}]) 

HTML:

<ion-content padding> 

    <div ng-controller="ClienteCtrl"> 
     <button ng-click="listaClientes()">Novo Cliente</button> 
     <!--<table> 
      <tr ng-repeat="cli in clientes"> 
       <td></td> 
      </tr> 
     </table>-->  
     <ion-item ng-repeat="cli in seleciona"> 
      {{cli.nome}} 
      <button ng-click="cadastraCliente({{cli.id}})">Novo</button> 
      <button ng-click="instala({{cli.id}}, {{cli.nome}})">Instalação</button> 
      <button ng-click="excluiCliente({{cli.id}}, {{cli.nome}})">Excluir</button> 
    </div> 

</ion-content> 

誰能幫助?

回答

1

您的代碼有很多的建築問題,但是這是非常正常的,當你開始新的東西。 :)

我在考慮與數據庫一起工作的基礎(我沒有測試),通過全局變量傳遞數據到控制器的總體方法是錯誤的,請不惜一切代價避免這種情況在angular/javascript世界中。

你需要考慮更多的假設模塊化或面向對象,並嘗試封裝此。如果你的代碼不會很脆弱並且容易出錯,因爲即使腳本的順序也會破壞它。

我做了一些調整你的代碼中看到波紋管:

工廠:

angular.module('sqlite', ['ionic', 'ngCordova']) 
.run(function ($ionicPlatform, $cordovaSQLite) { 
    $ionicPlatform.ready(function() { 
     var db = $cordovaSQLite.openDB({ name: 'rollers.db', location: 1 }); 

     $cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS clientes (id integer primary key, nome varchar(40))'); 
     $cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS instalacao (id integer primary key, idCliente int, dataInst datetime)'); 
     $cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS manutencao (id integer primary key, idCliente int, idInstalacao int, dataManut datetime)'); 
     $cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS equipamento (id integer primary key, idInstalacao int, idManutencao int, TC int autoincrement, posicao varcar(1), Rolo varchar(40), dataEquip datetime)'); 
    }); 
}) 
//I will not recommend you to use rootScope like that. 
//I added $q to work with the $cordovaSQLite promises 
.factory('clientesFactory', function ($cordovaSQLite, $q /*$rootScope*/) { 

    //local variables, no needs to be global 
    var db = $cordovaSQLite.openDB({ name: 'rollers.db', location: 1 }); 

    //better approach for legibility 
    return { 
     insert: insert, 
     selectTodos: selectTodos 
    }; 

    function insert(Nome) { 
     var query = 'INSERT INTO clientes (nome) VALUES (?);'; 
     var values = [Nome]; 

     //since this is a assynchronous method    
     //we can return this promise and let the caller lead with it 
     return $cordovaSQLite.execute(db, query, values) 
      .then(function() { 

       var deferred = $q.defer(); 
       // returns the data in the promise sucess 
       deferred.resolve('Cliente Cadastro com Sucesso!'); 

       /* 
       //This is really necessary? 
       //If so, why not to convert it in another method? 
       $cordovaSQLite.execute(db, 'SELECT max(id) as id from clientes', []).then(
        function (res) { 
         if (res.rows.length > 0) { 
          var valores = res.rows.item(0); 
          $rootScope.idCliente = valores.id; 
         } 
        } 
       );*/ 
      }) 
      .catch(function() { //promises have a catch method to capture the error 
       //returns the data with error 
       deferred.reject('Cliente não cadastrado. Estamos verificando o problema!'); 

      }); 
    } 

    function selectTodos(tab) { 
     var query = 'SELECT * FROM ' + tab; 

     //since this is a assynchronous method    
     //we can return this promise and let the caller lead with it 
     return $cordovaSQLite.execute(db, query, []) 
      .then(function (result) { 
       var deferred = $q.defer(); 

       if (!result.rows.length) { 
        //returns the data with error 
        deferred.reject('No data found!'); 
       } 

       var clienteselec = []; 
       for (var i = 0; i < result.rows.length; i++) { 
        clienteselec.push(result.rows.item(i)); 
       } 

       //returns the data in the promise sucess 
       deferred.resolve(clienteselec); 
      }) 
      .catch(function (err) { //promises have a catch method to capture the error 
       console.log('error' + err); 
      }); 
    } 
}) 

控制器:

.controller('ClienteCtrl', ['clientesFactory', '$scope', '$state', '$window', '$rootScope', function (clientesFactory, $scope, $state, $window, $rootScope) { 

    $scope.listaClientes = listaClientes; 
    $scope.seleciona = []; 


    function listaClientes() { 
     //Now, let the promise magic happens 
     //and lead with it here in the controller logic 
     clientesFactory.insert('teste') 
      .then(function (response) { 
       console.log(response); 
      }) 
      .catch(function (err) { 
       //use console.error to show erros :) 
       console.error(err); 
      }); 

     clientesFactory.selectTodos('clientes') 
      .then(function (response) { 
       $scope.clienteselec = response; 
      }) 
      .catch(function (err) { 
       //use console.error to show erros :) 
       console.error(err); 
      }); 
    } 
}]); 

希望,認爲不會改變在所有:

<ion-content padding> 

<div ng-controller="ClienteCtrl"> 
    <button ng-click="listaClientes()">Novo Cliente</button> 
    <ion-item ng-repeat="cli in seleciona"> 
     {{ cli.nome }} 
     <button ng-click="cadastraCliente({{cli.id}})">Novo</button> 
     <button ng-click="instala({{cli.id}}, {{cli.nome}})">Instalação</button> 
     <button ng-click="excluiCliente({{cli.id}}, {{cli.nome}})">Excluir</button> 
</div> 

免責聲明:我不在任何地方運行此代碼,所以我非常確定這不會按原樣運行。您將需要進行必要的調整,希望這將爲您提供一種整體方法來處理如何將數據從服務(工廠)傳遞到控制器,以及一些良好的編程實踐。如果您想了解更多關於如何以正確方式製作角度應用的信息,我強烈建議您查看John Papa的Angular Style Guide:https://github.com/johnpapa/angular-styleguide

乾杯,

+0

非常感謝您的幫助gvsrepins。我會測試你放在那裏的承諾,如果它有效的話,會作出迴應。 – FelipeF

+0

我很樂意幫助@FelipeF。 :)如果此答案符合您的需求,請將其標記爲您的問題的答案。謝謝。 – gvsrepins