AngularJS和promise值在调用本地函数时的效果-未定义
AngularJS and the effect of the promise value when calling a local function - undefined
我是Angular的新手,正在绕过一个我不想再使用的DB调用。在调用DB的代码的响应和访问存储变量的新代码(通过getter)之间,唯一的区别是响应对象的$promise
值是undefined
(在新代码中),而不是Object
(在旧代码中)。这种差异似乎导致了以下错误:TypeError: undefined is not a function
;我使用的是AngularJS v1.2.0-rc。3必须使用异步调用才能将$promise
值设置为Object
吗?或者有手动设置/强制转换的方法吗?
以下是一些代码片段:
工厂(QueryService):
var recentResponse = null;
var getRecentResponse = function() {
return recentResponse;
};
var doQuery = function (input, handler, errorHandler) {
MyResource.saveInput(input, function (response) {
// save JSON response locally (NEW!)
recentResponse = response;
// save JSON response to DB via handler (old)
handler(response);
},
function (errors) {
errorHandler(errors);
});
};
var getQueryById = function(id, handler) {
// query the DB
MyResource.getObjectWithId(id, function(response) {
handler(response);
});
};
return {
doQuery: doQuery,
getQueryById: getQueryById,
getRecentResponse: getRecentResponse
};
控制器:
function loadQueryById(id) {
// call the DB query
QueryService.getQueryById(id, function(response) {
$scope.query = response;
$scope.query.val2 = $scope.getVal2();
});
}
function loadLastQueryResponse() {
// load from local var
$scope.query = QueryService.getRecentResponse();
$scope.query.val2 = $scope.getVal2();
}
loadQueryById($routeParams.id);
loadLastQueryResponse();
$scope.getVal2 = function() {
return $scope.query.value2 ? JSON.parse($scope.query.value2) : "";
};
当loadQueryById()
被调用时,$scope.query
被设置为$promise
字段=Object
;当调用loadLastQueryResponse()
时,除了$promise
是undefined
之外,所有的$scope.query
字段都完全相同,并且以下行在尝试调用$scope.getVal2()
时失败并出现错误:
TypeError: undefined is not a function
at loadLastQueryResponse (MyController.js:20)
在这两种情况下,$scope.query.$resolved
字段都是true
。
我的Angular版本是否与此有关,或者我没有等待承诺的实现(因为我不需要)?我还尝试过用处理程序调用QueryService.getRecentResponse()
,也尝试过使用then()
格式(我可能正确实现了它,也可能没有正确实现它),但结果是一样的。
为了保护无辜者,函数和变量的名称已经更改。提前感谢!
正如@laurent在评论中回答的那样,问题是一旦请求不再异步调用DB,而是同步调用函数;因此CCD_ 20声明必须移动到CCD_。
- Jquery未定义函数正在停止其他操作
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- Uncaught ReferenceError:尝试在Android网络视图中访问时未定义函数
- jQuery文件上传和验证未定义函数
- 引用错误:未定义函数-Firefox
- res.render中出错,未定义函数
- 神秘的未定义函数
- 尝试使用函数和Ajax修改值时未定义函数
- 引用错误:未定义函数
- ReferenceError:未定义函数
- 在 Angular JS 中使用 ng-include 的未定义函数
- 未捕获的引用错误:未定义函数
- j查询工具提示引发错误:未定义函数
- 未捕获的引用错误: 未定义单击世界 -- 未定义函数
- JS:引用错误:未定义函数
- 茉莉花未定义函数
- Javascript 错误:未捕获的引用错误:未定义 [函数]
- 未定义函数
- 尽管 js 文件引用在标头中,但未定义函数
- Javascript 未定义函数错误