[英]AngularJS and the effect of the promise value when calling a local function - undefined
我真的是Angular的新手,正在绕过我不想再使用的数据库调用。 在调用数据库的代码的响应与访问我的新代码(通过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
field = Object
; 调用loadLastQueryResponse()
时,所有$scope.query
字段都完全相同,只是undefined
$promise
,并且以下行在尝试调用$scope.getVal2()
时失败并显示错误:
TypeError: undefined is not a function
at loadLastQueryResponse (MyController.js:20)
$scope.query.$resolved
字段在两种情况下均为true
。
我的Angular版本是否与此有关,或者我不是在等待实现承诺(因为我不需要这样做)? 我还尝试使用处理程序调用QueryService.getRecentResponse()
,还尝试使用then()
格式(我可能正确实施或未正确实施),但结果是相同的。
函数和变量名已更改,以保护无辜者。 提前致谢!
正如@laurent在评论中所回答的那样,问题是,一旦请求不再异步调用数据库,而是同步调用函数; 因此$scope.getVal2 = function () {..}
声明必须移至function loadLastQueryResponse(){..}
以便后者中的调用代码知道前者的函数实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.