2016-04-22 33 views
2

我是離子的新手。我想將數據添加到來自遠程服務器的SQLite中。我已經成功地將數據填充到list.so中,如何將這些數據存儲到sqlite中。這是我的代碼。我如何將這些數據傳遞給query.I無法做到這一點。如何使用離子將數據插入SQLite

service.js

angular.module('starter.service',[]). 
    factory('userServices',['$http',function($http){ 
    var users = []; 

    return { 
     get: function(){ 
     return $http.get("http://xxxxxxxxx-info").then(function(response){ 
      users = response.data; 

      return users; 

     }); 
     }, 
     remove:function(content){ 
     users.splice(users.indexOf(content),1); 
     }, 
     getUser:function(chatId) 
     { 
     for(var i=0; i<users.length;i++){ 
      if(users[i].content_id === parseInt(chatId)){ 
      return users[i]; 

      } 
     } 
     return null; 
     } 
    } 
    }]); 

controller.js

angular.module('shoppingPad.controller', []) 


     .controller('ChatCtrl', function ($scope, userServices, $ionicModal, $cordovaSQLite) { 
     console.log('inside controller'); 
     userServices.get().then(function (users) { 
      //users is an array of user objects 
      $scope.contents = users; 
      console.log($scope.contents); 
      var query = "INSERT INTO content (content_id, display_name) VALUES (?,?)"; 
      $cordovaSQLite.execute(db, query, [users.content_id, users.display_name]).then(function (res) { 
      alert(res); 
      alert('Inserted'); 
      }, function (e) { 
      alert('Error:' + e.message); 
      }); 
     }); 

回答

0

你在哪裏定義分貝?有必要等到設備準備就緒。

$ionicPlatform.ready(function() { 
    var db = $cordovaSQLite.openDB({ name: "my.db" }); 

    // just first time you need to define content table 
    $cordovaSQLite.execute(db,"CREATE TABLE content (content_id integer, display_name text)"); 

    userServices.get().then(function (users) { 
      //users is an array of user objects 
      $scope.contents = users; 
      console.log($scope.contents); 
      var query = "INSERT INTO content (content_id, display_name) VALUES (?,?)"; 
      $cordovaSQLite.execute(db, query, [users.content_id, users.display_name]).then(function (res) { 
      alert(res); 
      alert('Inserted'); 
      }, function (e) { 
      alert('Error:' + e.message); 
      }); 
    }); 
}); 

你確定,你的目標用戶看起來像

{ 
    "content_id":12, 
    "display_name":"hello world" 
} 

,而不是像

[ 
    { 
     "content_id":12, 
     "display_name":"hello world" 
    }, 
    { 
     "content_id":13, 
     "display_name":"stackoverflow" 
    }, 
    ... 
] 

我只問,因爲users聽起來像一個以上的條目。

+0

它包含多個條目 – sharvari

+0

然後,您必須遍歷每一個項目,並逐一添加到數據庫 –