我正在試圖讓這個工作正常。我已經嘗試過回調和承諾,並且對兩者均開放。我使用Joe Eames在Pluralsight類中制定的Mean Stack來模擬我的代碼。我仍然在學習,所以如果不正確,請原諒我的術語,但這裏是如何與代碼一起工作的,如下圖所示。角度回調或承諾陷阱返回價格
我的界面調用flQuestionCrudCtrl.createQuestion,調用flQuestionCrud.createNewQuestion調用flQuestion.Create。 flQuestion.Create向寫入mongodb集合的服務器發出http post請求。似乎一切正常,數據寫入數據庫,我可以看到每個控制檯日誌flQuestionCrud中的返回值。當我嘗試讀取flQuestionCrudCtrl中的「data」返回參數時,「錯誤:數據未定義」。我已經嘗試了回調和承諾的每一個組合,但不能讓它工作。你能看到我做錯了什麼嗎?
angular.module('app').controller('flQuestionCrudCtrl',function(flConstructDataService, flQuestionDataService, flQuestionCrud, flCachedReferenceData,flCachedQuestions, flAnswer, $scope, $location, $q, flIdentity, flNotifier,$timeout, $state) {
$scope.createQuestion = function() {
function doWorkAsync() {
return $timeout(flQuestionCrud.createNewQuestion(currentQuestionData), 10);
}
doWorkAsync()
.then(function(data) {
console.log("flQuestionCrudCtrl - Success " + data);
console.log("flQuestionCrudCtrl - Success Statement " + data.statement);
console.log("flQuestionCrudCtrl - Success Question id " + data._id);
currentQuestionData._id = data._id;
flQuestionDataService.setNewQuestionId(data._id);
console.log("flQuestionCrudCtrl - currentQuestionData._id " + currentQuestionData._id);
console.log("flQuestionCrudCtrl - flQuestionDataService.getNewQuestionId() " + flQuestionDataService.getNewQuestionId());
$state.go('questionUpdate');
})
.catch(function(err) {
console.log("flQuestionCrudCtrl - Error " + err);
$state.go('questionCreate');
})
.finally();
};
}
angular.module('app').factory('flQuestionCrud',function($http, $q, $state, $timeout, flQuestion){
return {
createNewQuestion: function(newQuestionData) {
console.log("Before - flQuestion.create");
function createQuestionDataAsync(questionData) {
console.log("flQuestionCrud - Before Call to create ")
var returnData;
flQuestion.create(questionData, function(data) {
console.log("flQuestionCrud - After Call to create ")
if (!data){
return Error("Error Creating Data");
//return null;
}
else {
console.log("flQuestionCrud - Try Section - Success " + data);
console.log("flQuestionCrud - Try Section - Success Statement " + data.statement);
console.log("flQuestionCrud - Try Section - Success Question id " + data._id);
}
return data;
});
}
createQuestionDataAsync(newQuestionData);
},
你得到當你試圖將「未定義」錯誤將數據記錄在doWorkAsync函數的'then'部分中? – user2085143
是的,第198行是當時我嘗試顯示語句的第二條日誌語句。第一個日誌語句顯示未定義。下面是第一條日誌語句的輸出,然後是錯誤。前 - flQuestion.create flQuestionCrud.js:4:13 flQuestionCrud - 之前調用創建flQuestionCrud.js:46:17個 flQuestionCrudCtrl - 成功未定義flQuestionCrudCtrl.js:197:17 錯誤:數據不確定 $ scope.createQuestion/<@http:// localhost:3030/app/questions/flQuestionCrudCtrl.js:198:17 processQueue @ http:// localhost:3030/vendor/angular/angular.js:14792:28 –