AngularJS和promise值在调用本地函数时的效果-未定义

AngularJS and the effect of the promise value when calling a local function - undefined

本文关键字:未定义 函数 promise 调用 AngularJS      更新时间:2023-09-26

我是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()时,除了$promiseundefined之外,所有的$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_。