2

在角度服务中考虑这种方法:

    select : function(table) {
        window.sqlitePlugin.openDatabase({
            name: 'smartLab.db',
            location: 'default'
        }, function success(db) {
            var defer = window.Q.defer();

            console.dir(defer);

            db.executeSql('SELECT * FROM ' + table, [], function success(rows) {
                var resp = [];

                for(var i = 0; i < rows.rows.length; i++) {
                    resp.push(rows.rows.item(i));
                }

                defer.resolve(resp);

            }, defer.reject)
        }, function error(err) {

        })
    }

我通过以下方式从另一个服务调用它:

DatabaseService.select(TBL_NAME).then(function(rows) {
  // logic goes here
});

我得到的错误是:

Uncaught TypeError: Cannot read property 'then' of undefined

我以前从未使用过 Q,但对 Promise 很熟悉,有什么东西会跳出本质上是错误的吗?很明显有什么...

4

2 回答 2

3

您永远不会从延迟对象返回承诺(单击此处了解更多信息)

select : function(table) {
    var defer = window.Q.defer();

    window.sqlitePlugin.openDatabase({
        name: 'smartLab.db',
        location: 'default'
    }, function success(db) {


        console.dir(defer);

        db.executeSql('SELECT * FROM ' + table, [], function success(rows) {
            var resp = [];

            for(var i = 0; i < rows.rows.length; i++) {
                resp.push(rows.rows.item(i));
            }

            defer.resolve(resp);

        }, defer.reject)
    }, function error(err) {

    });

    return defer.promise;
}
于 2017-07-25T22:09:26.113 回答
3

由于您使用的是 ionic/angular,因此您也可以使用Promise. 例如,我使用 DataProvider 指令:

public getJobs() {
    return new Promise((resolve, reject) => {
      this.sqlite.create({
        name: this.dbName,
        location: this.dbLoc
      })
      .then((db: SQLiteObject) => {
        var query = "SELECT * FROM user_jobs WHERE user_id=(?)";
        db.executeSql(query, [this.userId])
        .then((resp) => {
          console.log('Executed SELECT SQL:', resp.rows.length);
          resolve(resp);
        })
        .catch(e => console.log('db.executeSql error: ', JSON.stringify(e)));

      })
      .catch(e => console.log('sqlite.create error: ', e));

      });
  }

在任何页面中,您都可以轻松调用它:

this.dataProvider.getJobs().then((resp:any) => {
        if (resp.rows.length > 0) {
          for (var i = 0; i < resp.rows.length; i++) {
            let item = resp.rows.item(i);
            console.log(item);
          }
        }
      });
于 2017-12-20T14:56:18.303 回答