Sqlite - 无法返回选定的数据angularjs服务

时间:2016-03-15 08:17:25

标签: angularjs sqlite ionic-framework

在我的离子应用程序中。我创建了一个名为 webservice 的服务,使用angularjs从sqlite数据库中检索数据。正确选择数据并在控制台中获得结果它工作正常,但它总是返回 undefined

这是我的示例代码:

app.factory('webservice',function($http,$cordovaSQLite,$q){

    var obj = {};

    obj.getNote =  function(){
        var query = "SELECT subject, note FROM notes";
        var q = $q.defer();
        $cordovaSQLite.execute(db, query).then(function(res) {
            if(res.rows.length > 0) {               
                var data = res.rows;
                console.log(data); //Result - Working..
                q.resolve(res.rows); //Result - Undefined..
                return data; //Result - Undefined..
            } else {
                console.log("No results found");
                return false;
            }
        }, function (err) {
            console.error(err);
        });
    }

    return obj;

});

这是我的控制器:

app.controller('noteCtrl', function($scope,$state,webservice){

    $scope.getNote =  function(){
        console.log(webservice.getNote()); // Undefined.
    }

});

所以请尽量为我找到好的解决方案。

谢谢!

1 个答案:

答案 0 :(得分:4)

两件事。首先,您没有从服务中返回promise对象,其次,您没有在控制器中调用then函数。请尝试以下代码:

app.factory('webservice',function($http,$cordovaSQLite,$q){

    var obj = {};

    obj.getNote =  function(){
        var query = "SELECT subject, note FROM notes";
        var q = $q.defer(); //this is your deferred object
        $cordovaSQLite.execute(db, query).then(function(res) {
            if(res.rows.length > 0) {               
                var data = res.rows;
                console.log(data); //Result - Working..
                q.resolve(res.rows); //Result - Undefined..
                return data; //Result - Undefined..
            } else {
                console.log("No results found");
                q.reject("No results found"); 
                return false;
            }
        }, function (err) {
            q.reject(err);
            console.error(err);
        });

        return q.promise;       //This line was missing

    }

    return obj;

});

并在控制器中执行此操作:

 app.controller('noteCtrl', function($scope,$state,webservice){

    $scope.getNote =  function(){
        webservice.getNote().then(
            function(res){   //success callback
             console.log(res);  //this should be the resolved object
            },
            function(err){   //error callback
             console.log(err);  //this should be the rejected object
            });
    }

});