1
websqlからデータを読み込もうとしています。コードはコントローラにすべてを入れるとうまく動作しますが、コードを別のサービスに移動しても結果は返されません。私は、コントローラからではなくサービスからデータを取得したい。Angular JSはthen()を実行しません
のjavascript:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope', 'myService', '$q', function ($scope, myService, $q) {
$scope.count = 0;
$scope.connect = function() {
var deferred = $q.defer();
myService.method1().then(function(results){
$scope.count = results.rows.length;
},
function (error) {
console.log("Error");
}
);
}])
myApp.service('myService', function($q) {
var deferred = $q.defer();
this.method1 = function() {
var db = openDatabase('mydb2', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (3, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (4, "logmsg")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML = msg;
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
if(results.rows.length > 0) {
console.log("Inside resolve");
deferred.resolve(results);
$scope.$apply();
} else {
deferred.reject(response);
}
}, null);
});
return deferred.promise;
};
});
マークアップ:
<div ng-controller="MyCtrl">
{{count}}
<div id="status" name="status">Status Message</div>
</div>
JSfiddle:http://jsfiddle.net/pc97fgfg/9/
おそらく実行できないので、フィドルは無意味です –
'console.log("内部解決 ");'実行されますか?この行の –
、 'deferred.reject(response);' '応答'とは何ですか?薄い空気から抜かれた変数のようです。 –