0

在我的代码中,我有:

    var EntityResource = $resource('/api/:entityType', {}, {
        postEntity: { url: '/api/:entityType/', method: 'POST' },
        getEntity: { url: '/api/:entityType/:entityId', method: 'GET' },
        putEntity:     { url: '/api/:entityType/:entityId', method: 'PUT' },
        deleteEntity: { url: '/api/:entityType/:entityId', method: "DELETE" },
        getEntities: { url: '/api/:entityType/:action/:id', method: 'GET', isArray: true },
    });

然后我使用以下内容获取数据:

    getProjects: function (
            entityType,
            deptId) {
            var deferred = $q.defer();
            EntityResource.getEntities({
                action: "GetProjects",
                entityType: entityType,
                deptId: deptId
            },
               function (resp) {
                   deferred.resolve(resp);
               }
            );
            return deferred.promise;
        },

和以下调用getProjects:

            entityService.getProjects(
                'Project',
                $scope.option.selectedDept)
            .then(function (result) {
                $scope.grid.data = result;
            }, function (result) {
                $scope.grid.data = null;
            });

我认为不需要中间函数getProjects,我想直接使用$resource。

有人可以就我如何做到这一点给我一些建议吗?我查看了 $resource 的 AngularJS 文档,但对我来说不是很清楚。

4

1 回答 1

0

$resource 调用默认返回空数组,然后在收到响应时填充它们。如文档中所述

重要的是要意识到调用 $resource 对象方法会立即返回一个空引用(对象或数组取决于 isArray)。从服务器返回数据后,现有参考将填充实际数据。

资源上已经定义了默认的 5 种方法,get,save,query,remove,delete. 您可以直接调用它们,而不是像您所做的那样定义自己的postEntity,但 url 模板保持不变。

所以一旦你像这样定义资源

var entityResource = $resource('/api/:entityType');

你可以打电话

var entity=entityResource.get({entityType:1},function(data) {
    //The entity would be filled now
});

请参阅User文档中的示例

如果您想返回承诺,那么您必须将调用包装到您的服务调用中,就像您对 getProjects 所做的那样。

更新:根据您的评论,定义可能是

var entityResource = $resource('/api/:entityType/:action/:id')

现在如果你这样做

entityResource.get({},function(){})  // The query is to /api
entityResource.get({entityType:'et'},function(){})  // The query is to /api/et
entityResource.get({entityType:'et',:action:'a'},function(){})  // The query is to /api/et/a
entityResource.get({entityType:'et',:action:'a',id:1},function(){})  // The query is to /api/et/a/1

希望能帮助到你。

$resource 确实公开了 $promise 但它在返回值和后续调用上。

于 2013-09-03T05:45:49.440 回答