如何使用 Ionic sqlite return return 数据

How to return return data with Ionic sqlite

我是一个使用 sqlite 存储数据的 ionic 程序。当我 return 数据到视图时,它 return 什么都没有。

我设置了一个服务来获取数据。看起来像

read(){
    this.sqlite.create({
      name: DB_NAME,
      location: 'default'
    })
    .then((db: SQLiteObject) => {  
      db.executeSql('CREATE TABLE IF NOT EXISTS todos(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(32), datetime VARCHAR(32))', {})
        .then(() => console.log("Created Table OR NOT"))
        .catch(e => this.presentAlert(e));

      db.executeSql('SELECT * FROM todos ORDER BY id DESC', {})
      .then((response) => {
        if(response.rows.length > 0){
          for(var i=0; i < response.rows.length; i++){
            this.my_todos.push({
              id:response.rows.item(i).id, 
              name:response.rows.item(i).name, 
              datetime:response.rows.item(i).datetime
            })
          }
        }       
        //this.presentAlert(JSON.stringify(this.my_todos));
        return this.my_todos;
      })
      .catch(e => this.presentAlert(JSON.stringify(e)));
    })
    .catch(e => this.presentAlert(JSON.stringify(e)));
  }

在 home.ts 文件上,我尝试访问像

这样的服务
this.todos = this.todoService.read()

当我在控制台上登录 this.todos 时。它没有 return 任何东西。谁能帮帮我?...

//嗨, //你不能这样做this.todos = this.todoService.read()。 //你应该编写承诺从 sqlite 获取数据并在你的//组件中使用它们。 //我希望读取函数在服务文件中(todoService.ts)。改成 //this.

//Hi,
//You cannot do this this.todos = this.todoService.read().
//You should write promises to get data from sqlite and use them in your //component.
//I expect read function is in the service file(todoService.ts). Change it like //this.

    public read() {
return new Promise((resolve,reject) => {
var db = new SQLite();
        
        var query = "CREATE TABLE IF NOT EXISTS todos(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(32), datetime VARCHAR(32))";
        db.create({
          name: "data.db",
          location: "default"
        }).then((db1: SQLiteObject) => {
          db1.executeSql(query,[])
          .then((res) => {
            let todos = [];
            if(res.rows.length > 0 ) {
              todos.push(res.rows.item(0))
            }
            resolve(todos)
          },(error) => {
            reject(error);
          });
})

}
//  The promise returns an array of objects


In the page component 
// declare this
 public itemList : Array<Object>;
// In the constructor
this.itemList = [];

this.todoService.read().then((result) => {
this.itemList = <Array<Object>> result;
// you will get the retrieved data from sqlite from this array
console.log(this.itemList)
})
)


// This should work Please update me in case of any issues