【发布时间】:2014-12-29 22:28:17
【问题描述】:
我的 VisiteCtrl 中有一个调用“getItems()”的按钮:
<button type="button" ng-click="getItems();">Populate</button>
这是我的 VisiteCtrl :
function VisiteCtrl($scope, visiteService) {
$scope.items = [];
$scope.getItems = function() {
var promise = visiteService.getItems();
promise.then(function(items) {
$scope.items = items;
});
};
}
还有我的“visiteService”:
var module = angular.module('app', []);
module.service('visiteService', function($q) {
this.getItems = function() {
var deferred, result = [];
deferred = $q.defer();
var db = window.openDatabase('database', '1.0', 'database', 200000);
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS todos(id integer primary key, item text, qty integer, type varchar(50))");
/*tx.executeSql("DELETE FROM todos;");
tx.executeSql("INSERT INTO todos(id, item, qty, type) VALUES (null, 'Oignon', 1, 'Course')");
tx.executeSql("INSERT INTO todos(id, item, qty, type) VALUES (null, 'Viande', 2, 'Course')");
tx.executeSql("INSERT INTO todos(id, item, qty, type) VALUES (null, 'Dormir', 1, 'Autre')");*/
tx.executeSql("SELECT * FROM todos", [], function(tx, res) {
for(var i = 0; i < res.rows.length; i++) {
result.push({
id : res.rows.item(i).id,
item : res.rows.item(i).item,
qty : res.rows.item(i).qty,
type : res.rows.item(i).type
});
}
deferred.resolve(result);
},
function(tx, err) {
console.log(err);
});
},
function(err) {
console.log(err);
});
return deferred.promise;
}
});
第一次点击我的按钮: - 调用服务没有错误 - “deferred.resolve(结果);”也被称为 - 包含数据的结果(console.log 显示包含)。 - ...但是“promise.then(...)”从未调用过。
在我第二次点击之后,除了“promise.then(...)”之外,其他的东西现在都被调用了。 $scope.items 包含我的结果(打印在我的页面中)。
我修改了我的 Ctrl 来测试一些东西:
function VisiteCtrl($scope, visiteService) {
$scope.items = [];
$scope.called = false;
$scope.getItems = function() {
if (!$scope.called) {
$scope.called = true;
alert("hip");
var promise = visiteService.getItems();
promise.then(function(items) {
alert("hop");
$scope.items = items;
});
}
};
}
第一次点击:我有“臀部” 第二次点击:我有“跳”
好像第二次点击resolve de $q。
我完全迷路了。你不知道吗?
提前感谢您的回答。
【问题讨论】:
-
尝试在服务中使用 $rootScope.$apply() 以便承诺在角度世界中得到解决。
-
是的,
db回调是在 Angular 不知情的情况下发生的,$scope.$apply()应该可以解决问题。仅供参考,无需在$apply()内部执行$rootScope.$apply(),自动使用$rootScope服务。