gpt4 book ai didi

javascript - Angular JS promise then() 不执行

转载 作者:行者123 更新时间:2023-11-28 05:35:53 24 4
gpt4 key购买 nike

我正在尝试从 websql 读取数据。当我将所有内容放入 Controller 中时,代码运行良好,但当我将代码移动到单独的服务中时,它不会返回任何结果。我想从服务而不是 Controller 获取数据。

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/

最佳答案

我在 deferred.resolve(results); 之后使用 $rootScope.$apply(); 得到了预期的结果。

更新的 fiddle 是 http://jsfiddle.net/pc97fgfg/14/

感谢neda的建议。

关于javascript - Angular JS promise then() 不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39362747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com