0

我的应用程序中有 2 个列表,用户应该将项目从一个列表拖放到另一个列表。
当用户从一个列表中删除一个元素到另一个列表时,必须向服务器端代码发出请求以更新数据库中的字段 (SelectedForDiscussion)。
这是我的控制器中的代码:

$scope.$watch("questionsDiscuss", function (value) {
    var question = $.Enumerable.From($scope.questionsDiscuss).Where(function (item) { return !item.SelectedForDiscussion }).FirstOrDefault()
    if (question != undefined) {

        questionSelectionService.UpdateQuestionSelectionStatus(question.Id, true)
        .then(function (output) {

            var question = $.Enumerable.From($scope.questionsDiscuss)
                                .Where(function (item) { return item.Id == output.data.questionId })
                                .FirstOrDefault();
            var index = $.Enumerable.From($scope.questionsDiscuss).IndexOf(question);

            if (question != undefined)
                if (output.data.result != "success") {
                    $scope.questionsDiscuss.splice(index, 1);
                    $scope.questionsReceived.splice(0, 0, question);
                }
                else {
                    question.SelectedForDiscussion = true;
                    $scope.questionsDiscuss[index] = question;
                }
        });
    }
    else {
        var question = $.Enumerable.From($scope.questionsReceived).Where(function (item) { return item.SelectedForDiscussion }).FirstOrDefault();
        if (question != undefined) {
            questionSelectionService.UpdateQuestionSelectionStatus(question.Id, false)
            .then(function (output) {
                var question = $.Enumerable.From($scope.questionsReceived)
                                .Where(function (item) { return item.Id == output.data.questionId })
                                .FirstOrDefault();
                var index = $.Enumerable.From($scope.questionsReceived).IndexOf(question);

                if (question != undefined)
                    if (output.data.result != "success") {
                        $scope.questionsReceived.splice(index, 1);
                        $scope.questionsDiscuss.splice(0, 0, question);
                    }
                    else {
                        question.SelectedForDiscussion = false;
                        $scope.questionsReceived[index] = question;
                    }
            });
        }

    }

}, true);

我在 Firebug 中的以下行放置了 4 个 javascript 断点:
其中 2 个位于以下行:

if (question != undefined) {

一个在:

var question = $.Enumerable.From($scope.questionsDiscuss)
    .Where(function (item) { 
        return item.Id == output.data.questionId 
     }) 
    .FirstOrDefault();

另一个在:

var question = $.Enumerable.From($scope.questionsReceived)
    .Where(function (item) { 
         return item.Id == output.data.questionId 
     })
    .FirstOrDefault();

会发生以下情况:

断点在:

if (question != undefined) {

总能达到。

断点在

var question = $.Enumerable.From($scope.questionsDiscuss) 
    .Where(function (item) { 
         return item.Id == output.data.questionId 
    })
    .FirstOrDefault();

也达到了。
另一个永远达不到。
两个响应都正常(响应代码 200)。
一切都应该完美运行,但永远不会达到第二个承诺中的 then 子句。
谁能告诉我我做错了什么?
服务器端应用程序是一个用 C# 编写的 ASP.NET MVC 应用程序。

编辑 1:我知道为什么会发生这种情况,并且我有一个解决方法。我仍然对实际的解决方案感兴趣。
问题是 angularjs 抛出一个错误,然后在第二次调用 $http 时将其吞下。错误是:

已经在消化

我认为这是因为在我的指令中我有以下代码:

dndfunc = function (scope, element, attrs) {

    // contains the args for this component
    var args = attrs.dndBetweenList.split(',');
    // contains the args for the target
    var targetArgs = $('#' + args[1]).attr('dnd-between-list').split(',');

    // variables used for dnd
    var toUpdate;
    var target;
    var startIndex = -1;

    // watch the model, so we always know what element
    // is at a specific position
    scope.$watch(args[0], function (value) {
        toUpdate = value;
    }, true);

    // also watch for changes in the target list
    scope.$watch(targetArgs[0], function (value) {
        target = value;
    }, true);

    // use jquery to make the element sortable (dnd). This is called
    // when the element is rendered
    $(element[0]).sortable({
        items: 'div',
        start: function (event, ui) {
            // on start we define where the item is dragged from
            startIndex = ($(ui.item).index());
        },
        stop: function (event, ui) {
            var newParent = ui.item[0].parentNode.id;

            // on stop we determine the new index of the
            // item and store it there
            var newIndex = ($(ui.item).index());
            var toMove = toUpdate[startIndex];

            // we need to remove him from the configured model
            toUpdate.splice(startIndex, 1);

            if (newParent == args[1]) {
                // and add it to the linked list
                target.splice(newIndex, 0, toMove);
            } else {
                toUpdate.splice(newIndex, 0, toMove);
            }

            // we move items in the array, if we want
            // to trigger an update in angular use $apply()
            // since we're outside angulars lifecycle
            scope.$apply(targetArgs[0]);
            scope.$apply(args[0]);
        },
        connectWith: '#' + args[1]
    })
}

我认为最后有 2 个调用会触发一个新的摘要周期。
无论如何,我通过在应用调用之前添加此调用来修复它:

            if (scope.updateLists != undefined)
                scope.updateLists();

并将所有代码从手表移到 updateLists 函数中。

另外因为人们提到该服务与它有关,所以我将相关代码粘贴在其中:

GetQuestionsReceived: function (eid, criteria, page, rows) {

    var promise = this.GetQuestionsReceivedInternal(eid,criteria, page, rows).then(function (response) {
        // The return value gets picked up by the then in the controller.
        return response;
    });
    // Return the promise to the controller
    return promise;
},

GetQuestionsReceivedInternal: function (eid, criteria, page, rows) {

    return $http({ method: 'GET',
        url: '../QuestionManagement/GetQuestions?eventId='+eid+'&page=1&rows=5&'+serialize(criteria)
    }).
      success(function (data, status, headers, config) {
          // this callback will be called asynchronously
          // when the response is available
          results = data;
      }).
      error(function (data, status, headers, config) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
          if (window.console && console.log) {
              console.log("Could not obtain questions received. Error:" + data + "Status:" + status + "Headers:" + headers + "Config:" + config);
          }
      });
},

  GetQuestionsDiscuss: function (eid,criteria, page, rows) {

    var promise = this.GetQuestionsDiscussInternal(eid,criteria, page, rows).then(function (response) {
        // The return value gets picked up by the then in the controller.
        return response;
    });
    // Return the promise to the controller
    return promise;
},

GetQuestionsDiscussInternal: function (eid,criteria, page, rows) {

    return $http({ method: 'GET',
        url: '../QuestionManagement/GetQuestions?eventId=' + eid + '&page=1&rows=5&' + serialize(criteria)
    }).
      success(function (data, status, headers, config) {
          // this callback will be called asynchronously
          // when the response is available
          response = data;
      }).
      error(function (data, status, headers, config) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
          if (window.console && console.log) {
              console.log("Could not obtain questions received. Error:" + data + "Status:" + status + "Headers:" + headers + "Config:" + config);
          }
      });

},
4

1 回答 1

0

你有两个非常相似的代码块,它们可以被概括并放在一个函数包装器中,留下一个非常简单的调用函数。

如果你能把所有东西都变成那种形式,那么我认为你会发现它更容易调试。

这是一个尝试这样做:

function updateSelectionStatus(qA, qB, bool) {
    var en = $.Enumerable.From(qA);
    var question = en.Where(function (item) {
        return bool ? !item.SelectedForDiscussion : item.SelectedForDiscussion;
    }).FirstOrDefault();
    if(question) {
        questionSelectionService.UpdateQuestionSelectionStatus(question.Id, bool).then(function (output) {
            if (output.data.result == "success") {
                question.SelectedForDiscussion = bool;
            }
            else {
                qA.splice(en.IndexOf(question), 1);
                qB.unshift(question);
            }
        });
    }
    return question;
}

$scope.$watch("questionsDiscuss", function (value) {
    if (!updateSelectionStatus($scope.questionsDiscuss, $scope.questionsReceived, true) {
        updateSelectionStatus($scope.questionsReceived, $scope.questionsDiscuss, false);
    }
}, true);

我可能做了一些错误的假设并且过于简化(例如清除内部$.Enumerable.From,这似乎重新选择了与外部相同的问题),因此您可能需要重新编写我的代码。

我在这里提倡一个原则,而不是提供一个解决方案。

于 2013-03-01T02:18:33.890 回答