【问题标题】:Timeout on angularjs callangularjs调用超时
【发布时间】:2016-09-13 21:38:39
【问题描述】:

我确定这个问题已经被问过很多次了,但我……找不到。现在是晚上 10:30,我得把这个留给你们!

基本上,我有两次调用 json 服务器方法 - 更新数据并获取新总数。从逻辑上讲,首先调用更新数据,通过 $emit 发送通知,获取新的总数。不幸的是,当我在服务器控制器上设置断点时,GetAlertTotals 在 SetAlertRead 之前被调用,所以返回了错误的数据。

“总计”代码在另一个控制器中,因此 $emit/publish/subscribe:

$scope.$on('RefreshUnreadItemsCounter', function () {
    $scope.alertCount = $scope.GetAlertCount();
    $scope.alertTotals = $scope.GetAlertTotals();
    $scope.$apply();
});

数据位于 uiGrid 中,具有以下(部分)定义:

    $scope.gridOptions.onRegisterApi = function (gridApi) {
    $scope.gridApi = gridApi;
    $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.EDIT);

    $scope.gridApi.selection.on.rowSelectionChanged($scope, function (row) {
        var authorisationToken = $('input[name="__RequestVerificationToken"]').val();

        row.entity.AlertSeen = true;
        $scope.message = row.entity.Message;
        $http({
            url: '/Alerts/SetAlertRead',
            contentType: "application/json; charset=utf-8",
            method: 'POST',
            data: { rowId: row.entity.UserAlertsId },
            headers: { '__RequestVerificationToken': authorisationToken }
        });
        $scope.$emit('RefreshUnreadItemsCounter');
    });

用户单击一行以显示与该行关联的数据并“读取”它,通过 json 调用 (/Alert/SetAlertRead) 触发数据更新。我假设我在 $emit 调用之前设置了一个超时,以便给承诺时间来执行 json 调用,但我不确定如何。

请帮忙!如果您不介意,我将需要尽可能多的代码!再次感谢。

【问题讨论】:

    标签: angularjs json timeout ui-grid


    【解决方案1】:

    您立即致电$scope.$emit('RefreshUnreadItemsCounter');,而没有机会解决或拒绝 $http 请求。您可以使用finally() 覆盖这两种情况,或者使用then(successFunction, errorFunction) 分别处理解决和拒绝情况。尝试将您的代码更改为:

    $scope.gridOptions.onRegisterApi = function (gridApi) {
    $scope.gridApi = gridApi;
    $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.EDIT);
    
    $scope.gridApi.selection.on.rowSelectionChanged($scope, function (row) {
        var authorisationToken = $('input[name="__RequestVerificationToken"]').val();
    
        row.entity.AlertSeen = true;
        $scope.message = row.entity.Message;
        $http({
            url: '/Alerts/SetAlertRead',
            contentType: "application/json; charset=utf-8",
            method: 'POST',
            data: { rowId: row.entity.UserAlertsId },
            headers: { '__RequestVerificationToken': authorisationToken }
        }).then(function (response) {
          $scope.$emit('RefreshUnreadItemsCounter');
        }, function (error) {
          // case of rejected promise
        });
    
    });
    

    【讨论】:

    • 非常感谢 Andriy - 完美地解决了这个问题。我无法为你的答案投票,因为我还没有问足够多的问题……我才注册两年……
    猜你喜欢
    • 2014-06-15
    • 2015-06-21
    • 1970-01-01
    • 2019-04-21
    • 2013-12-20
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    相关资源
    最近更新 更多