1

$http を使用して AJAX 呼び出しを行うことにより、最初にいくつかのデータをロードするサービスを作成しようとしています。

私は次のようなものを見ています:

app.factory('entityFactory', function() {
    var service = {};

    var entities = {};

    // Load the entities using $http

    service.getEntityById(entityId)
    {
        return entities[entityId];
    }

    return service;
});

app.controller('EntityController', ['$scope', '$routeParams', 'entityFactory', function($scope, $routeParams, entityFactory) {
    $scope.entity = entityFactory.getEntityById($routeParams['entityId']);
}]);

を使用してエンティティを返す前に、エンティティが完全に読み込まれていることを確認したいと思いgetEntityByIdます。

これを行う正しい方法を教えてください。私が知っている 1 つの方法は、同期 AJAX 呼び出しを行うことですが、他に良い方法はありますか? この場合、より良い方法でプロミスを使用できますか?

4

3 に答える 3

1

$q を使用して、サービスが初期化されているかどうかを確認してみました。私にとっては十分にきれいです。他の方法は大歓迎です:)。

app.factory('entityFactory', function($q, $http) {
    var service = {};

    var _entities = {};
    var _initialized = $q.defer();

    $http({method: 'GET', url: '/getData'})
        .success(function(data, status, headers, config) {
            if (data.success)
            {
                _entities = data.entities;
            }

            _initialized.resolve(true);
        })
        .error(function(data, status, headers, config) {
            _initialized.reject('Unexpected error occurred :(.');
        });

    service.getEntityById(entityId)
    {
        return entities[entityId];
    }

    service.initialized = _initialized.promise;

    return service;
});

app.controller('EntityController', ['$scope', '$routeParams', 'entityFactory', function($scope, $routeParams, entityFactory) {
    entityFactory.initialized.then(function() {
        $scope.entity = entityFactory.getEntityById($routeParams['entityId']);
    });
}]);
于 2014-10-10T02:37:47.953 に答える
0

ファクトリ内でコールバックを利用して、最初の呼び出しでデータを保存し、その後のすべての呼び出しでサービスからデータを受け取ることができます。

app.factory('entityFactory', function() {
    var service = {};

    var entities = null;

    // Load the entities using $http
    service.getEntityById(entityId, callback)
    {
        if (entities == null) {
            $http(options).success(function(data) {
                entities = data;
                callback(data);
            });
        } else {
            callback(entities);
        }
    }

    return service;
});

そして、これを使用できます:

entityFactory.getEntityById(id, function(entities) {
    //console.log(entities);
});
于 2014-10-10T02:27:11.503 に答える