2017-08-20 5 views
1

私は角度のあるプロジェクトに取り組んでいます。私はいくつかのデータといくつかのアクションでグリッドを持っています。

onclick関数のアクションの1つをクリックすると、ajaxリクエストは、生涯のプロセスで一度であるサーバー側に移動しています。

しかし、最初の要求の応答が来る前にユーザーがアクションボタンを連続してクリックすると、同じ呼び出しがサーバーに2回以上送信され、エラーが発生します。

私は複数の要求からそれを防ぐことはできませんが、私はajax要求の前にアクションボタンを無効にしようとしました。 2番目のリクエストをブロックする方法はありますか?

私のコードは

$http({ 
    method: 'POST', 
    url: urls.api_url_serv + 'notification/read?token=' + token, 
    transformRequest: transformRequestAsFormPost, 
    withCredentials: false, 
    headers: { 
    'Content-Type': 'application/x-www-form-urlencoded' 
    }, 
    data: { 
    notification_id: notification_id 
    } 
}).then(function(response) { 
    var data = response.data; 
    //Some actions 

}).catch(function(response) { 
    var status = response.status; 

    // Some actions 

}); 


<span ng-class="{'disabled': read_disable}"> 
<i class="fa fa-envelope" ng-click="MarkAsReadNotification(row.id)"></i> 
</span> 
+2

リクエストが作成された後でブロックするのではなく、デバウンスを試みて1回の呼び出しだけがトリガーされましたか? – ssube

+0

https://stackoverflow.com/questions/13320015/how-to-write-a-debounce-service-in-angularjs – mplungjan

+0

@ssubeわかりません。ボタンを無効にすることを意味しますか?私はすでにonclick関数のボタンを無効にしています – Salini

答えて

0

あなたは(簡単な方法でthisを使用するES6構文を使用した)例

this.makeRequest =() => { 
    if (!this.request) { 
    this.request = $http({ 
     method: 'POST', 
     url: urls.api_url_serv + 'notification/read?token=' + token, 
     transformRequest: transformRequestAsFormPost, 
     withCredentials: false, 
     headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
     }, 
     data: { notification_id } 
    }); 

    this.request.success((data) => { 
     // If you want let the user do a request, after this one is finished 
     this.request = undefined 
    }) 
    } 
} 
のためにそれを慣用的な方法を行うことができますです
0
<button ng-click="submit()" ng-disabled="disableButton"> 
    Submit 
</button> 
$scope.submit = function() { 
    $scope.disableButton = true; 
    return $http(config) 
     .then(function(response) { 
     var data = response.data; 
     //Some actions 
     return response.data; 

    }).catch(function(response) { 
     var status = response.status; 

     // Some actions 
     throw response; 

    }).finally(function() { 
     $scope.disableButton = false; 
    }); 
}; 

XHRを開始する前に、ボタンを無効にします、ボタンを無効ng-disabled directiveを使用するには。 .finallyブロックを使用して、要求が完了または拒否されたときにボタンを再度有効にします。

+0

私はこれを試しましたが、同じリクエストを送信してから数秒以内にボタンをクリックすると – Salini

関連する問題