我真正的新角度和我工作的繞過DB調用,我不希望使用任何更多。從調用訪問一個存儲變量(通過getter)數據庫和我的新代碼的代碼響應之間,唯一的區別是,響應對象的$promise
值undefined
(新代碼),而不是Object
(在舊代碼)。這種差異似乎導致以下錯誤:TypeError: undefined is not a function
;我正在使用AngularJS v1.2.0-rc.3我必須使用異步調用來將$promise
的值設置爲Object
還是有辦法手動設置/投射它?AngularJS和承諾值的調用本地功能時的效果 - 未定義
這裏有一些代碼段:
廠(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()
被調用時,所有的$scope.query
領域是完全不同的$promise
同樣是undefined
,並試圖調用$scope.getVal2()
時,以下行失敗,錯誤:
TypeError: undefined is not a function
at loadLastQueryResponse (MyController.js:20)
的$scope.query.$resolved
場是在兩種情況下true
。
難道我的角度版本有什麼關係呢,或者說我不是在等待一個承諾要滿足(因爲我並不需要是)事實?我也試着用處理程序調用QueryService.getRecentResponse()
,並且我也嘗試過使用then()
格式(我可能沒有正確實現),但結果是一樣的。
功能和變量名已被更改以保護無辜者。提前致謝!
,如果你移動的語句$ scope.getVal2 =函數(){..}上述 功能loadLastQueryResponse(){..}? – laurent
其中是'getRecentQueryResponse'的代碼。你能分享完整的服務代碼嗎 – harishr
工廠實際返回哪些方法? – charlietfl