サーバーからデータを取得するサービスがあるとします。非同期で、AngularJS $http サービスを使用していません。
Angular で非同期処理を行うときは、Promise を使用$q
します。しかし、問題が 1 つあります。promise は の後にのみ解決され$digest
ます。
これを修正するには、次の 2 つの方法があります。
1)$timeout
var defer = $q.defer();
$.getJSON('http://example.com/my.json')
.success(function (data) {
$timeout(function () {
defer.resolve(data);
});
});
return defer.promise;
2)$rootScope.$apply()
var defer = $q.defer();
$.getJSON('http://example.com/my.json')
.success(function (data) {
defer.resolve(data);
});
if (!$rootScope.$$phase) $rootScope.$apply();
AngularJS$http
サービスでは、2 番目のバリアントが使用されます。
両方の違いは何ですか?また、そのようなことを行う適切な方法は何ですか?
実際に両方の方法を試すことができます: http://jsbin.com/otakaw/3/edit