0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

angularjsでresourceをキャンセルする方法

0
Posted at

angularjsのngRouteを使ってシングルページWEBアプリケーションを作っていると、画面遷移した時に前画面の通信中のajaxをキャンセルしたいなと思いました。

$q.defer();

調べてみるとどうやらこのメソッドを使うとそれが実現できるようです。

で、僕はこんな感じで実装しました。

// ajaxのtaskを監視する変数を初期化します
$scope.ajax_tasks = null;

// 各ページで実行されるajaxを最初にscopeに入れます。
$scope.$on('$routeChangeSuccess', function(angularEvent, current, previous){
	$scope.ajax_tasks = $q.defer();
});

// resourceのtimeoutメソッドにtaskを入れます
$resource('endpoint url', {}, {save: {timeout:$scope.ajax_tasks.promise}}),

// ページ遷移のアクションが走ると前ページの通信中ajaxを全てキャンセルします
$scope.$on('$routeChangeStart', function(event, next, current){
	if($scope.ajax_tasks) $scope.ajax_tasks.resolve('cancelled');
});

scopeじゃなくてサービスでもOK

$httpでも同じようにtimeoutにpromise入れれば動作するみたいです。

以上、angularjsでresourceをキャンセルする方法でしたー

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?