More Related Content
Similar to AngularJSでの非同期処理の話
Similar to AngularJSでの非同期処理の話 (20)
More from Yosuke Onoue (18)
AngularJSでの非同期処理の話
- 6. 目次
1. 遅延処理 - $timeout!
2. HTTPアクセス - $http!
3. REST APIサーバーへのアクセス - ngResource!
4. Promiseを提供する - $q!
5. ngRouteとresolve
- 7. 目次
1. 遅延処理 - $timeout!
2. HTTPアクセス - $http!
3. REST APIサーバーへのアクセス - ngResource!
4. Promiseを提供する - $q!
5. ngRouteとresolve
- 9. $timeoutのサンプル
<div ng-app>
<div ng-controller="TimeoutExample">
<span>{{str}}</span>
<button ng-click="cancel()">Cancel</button>
</div>
</div>
function TimeoutExample($scope, $timeout) {
$scope.str = 'Prompt Result';
var promise = $timeout(function() {
$scope.str = prompt('Input Message');
}, 2000);
$scope.cancel = function() {
$timeout.cancel(promise);
$scope.str = 'Canceled';
};
}
http://jsfiddle.net/likr/2NMyP/
$timeoutで、2秒後にプロンプトを
表示して、入力をビューに表示する
$timeout.cancelに$timeoutの
戻り値を渡すことで処理の中止
$timeoutを依存性注入する
- 11. setTimeoutじゃダメなの?
function TimeoutExample($scope) {
$scope.str = 'Prompt Result';
!
var timeoutId = setTimeout(function () {
$scope.str = prompt('Input Message');
}, 2000);
!
$scope.cancel = function () {
clearTimeout(timeoutId);
$scope.str = 'Canceled';
};
}
http://jsfiddle.net/likr/243ja/
function TimeoutExample($scope) {
$scope.str = 'Prompt Result';
!
var timeoutId = setTimeout(function () {
$scope.$apply(function () {
$scope.str = prompt('Input Message');
});
}, 2000);
!
$scope.cancel = function () {
clearTimeout(timeoutId);
$scope.str = 'Canceled';
};
}
データバインドを反映させるために$scope.$applyが必要
http://jsfiddle.net/likr/243ja/2/
- 13. $timeoutとpromiseのサンプル
function TimeoutExample($scope, $timeout) {
$scope.str = 'Prompt Result';
$scope.status = 'Pending';
!
var promise = $timeout(function () {
$scope.str = prompt('Input Message');
}, 2000);
!
promise.then(function () {
$scope.status = 'Fullfilled';
});
promise.catch(function () {
$scope.status = 'Rejected';
});
!
$scope.cancel = function () {
$timeout.cancel(promise);
$scope.str = 'Canceled';
};
}
http://jsfiddle.net/likr/2NMyP/1/
$timeoutのpromiseに成功時、
失敗時のコールバックを登録
- 14. 目次
1. 遅延処理 - $timeout!
2. HTTPアクセス - $http!
3. REST APIサーバーへのアクセス - ngResource!
4. Promiseを提供する - $q!
5. ngRouteとresolve
- 15. $http
✤ HTTPサーバーへとの通信を行う!
✤ GET / POST / PUT / DELETE / HEAD!
✤ JSONP!
✤ 使い方
https://docs.angularjs.org/api/ng/service/$http
$http.get(url[, config])
$http.post(url[, config])
…
$http(config)
- 16. $httpのサンプル
function HttpExample($scope, $http) {
$http.get('http://example.com/')
.then(function(response) {
$scope.data = response.data;
});
}
http://jsfiddle.net/likr/ct6Jn/
function HttpExample($scope, $http) {
$http({
method: 'get',
url: 'http://example.com/'
}).then(function(response) {
$scope.data = response.data;
});
}
methodとurlを指定して$httpを呼び出す
$httpを依存性注入する
$httpはPromiseを返すのでthenで!
通信成功、失敗時の処理ができる
$http.getは$httpのショートカット
- 18. HttpPromise
✤ HttpPromise!
✤ $httpが返すPromise!
✤ thenの代わりにsuccessとerrorが使える
function HttpExample($scope, $http) {
$http.get('http://gdgkobe-ng-guestbook.appspot.com/greetings')
.success(function(response) {
$scope.data = response.data;
})
.error(function(reason) {
});
}
- 20. 目次
1. 遅延処理 - $timeout!
2. HTTPアクセス - $http!
3. REST APIサーバーへのアクセス - ngResource!
4. Promiseを提供する - $q!
5. ngRouteとresolve
- 21. ngResource
✤ REST APIサーバーとの通信を便利にするモジュール!
✤ REST APIサーバーの例
https://docs.angularjs.org/api/ngResource
Method URL 処理
GET http://example.com/greetings greeting
GET http://example.com/greetings/1 ID1
POST http://example.com/greetings 新しい
PUT http://example.com/greetings/1 ID1
DELETE http://example.com/greetings/1 ID1
- 24. Resourceの利用
✤ データ取得!
!
!
✤ データ保存
var Greeting = $resource('http://example.com/greetings/:id');
!
var greetings = Greeting.query();
var newGreeting = new Greeting();
newGreeting.content = 'hello';
newGreeting.$save();
- 25. Resourceの遅延処理
var app = angular.module('example', ['ngResource']);
!
app.factory('Greeting', function($resource) {
return $resource('http://gdgkobe-ng-guestbook.appsp
});
!
app.controller('Main', function(Greeting) {
var greetings = Greeting.query();
greetings.$promise
.then(function() {
console.log(greetings);
});
console.log(greetings);
});
Resourceのメソッドはプレースホルダーを
返して、処理が完了した時点で内容を挿入する
http://jsfiddle.net/likr/BHS5v/
- 27. 目次
1. 遅延処理 - $timeout!
2. HTTPアクセス - $http!
3. REST APIサーバーへのアクセス - ngResource!
4. Promiseを提供する - $q!
5. ngRouteとresolve
- 31. $qのサンプル1
var app = angular.module('q-example', []);
!
app.factory('d3get', function($q) {
return function(xhr) {
var deferred = $q.defer();
xhr
.on('load', function(data) {
deferred.resolve(data);
})
.on('error', function(status) {
deferred.reject(status);
})
.get();
return deferred.promise;
};
})
!
app.controller('Main', function(d3get) {
d3get(d3.csv('http://example.com/data.csv'))
.then(function(data) {
// TODO
});
});
D3.jsのxhr系関数をラップしてみる
$q.deferでdeferredオブジェクトを作成
データ取得が成功したらresolve
promiseオブジェクトを返す
thenでデータ取得後の処理を行う
loadDataをラップした関数をfactoryで提供
データ取得が失敗したらreject
- 32. $qのサンプル2
function getData(url) {
return $.get(url);
}
!
!
function Main($q) {
$q.when(getData('http://example.com/'))
.then(function(data) {
// TODO
});
});
jQueryのAJAX関数をラップしてみる
AngularJSとは関係のない、
jQueryXHR(Promise)を返す関数
$q.whenでラップすると!
$scope.$applyの手間等が不要
- 33. 目次
1. 遅延処理 - $timeout!
2. HTTPアクセス - $http!
3. REST APIサーバーへのアクセス - ngResource!
4. Promiseを提供する - $q!
5. ngRouteとresolve
- 36. ngRouteのresolve
var app = angular.module('resolve-example', ['ngRoute']);
!
app.config(function($routeProvider) {
$routeProvider.when('/', {
template: '{{data}}',
controller: function($scope, response) {
$scope.data = response.data;
},
resolve: {
response: function($http) {
return $http.get('http://example.com/');
}
}
});
});
resolveの要素がPromiseを返した場合、
全てのPromiseがresolveされてからコン
トローラーの処理を行う