【问题标题】:What's the best practice for handling loading child resources in ngResource?在 ngResource 中处理加载子资源的最佳实践是什么?
【发布时间】:2013-09-25 04:50:15
【问题描述】:

上下文:我是 Angular 新手,感觉更像是“在 AngularJS 中做这件事的正确方法是什么”之类的问题。

我的 API 后端有几个相关的对象,我需要请求这些对象并将它们组合成一个连贯的用户界面。它可以建模为订阅中心的东西,所以我有:Subscription hasMany Subscription_Items, belongsTo Source。

我想要做的是查找用户的订阅 (/api/subscriptions?user_id=1),它为我提供了一些 JSON,其中包含一个 subscription_item_ids=[1,2,3 ...] 数组。然后我想查询这些 id,并在 source_id 上查询服务器以提取共享信息,然后将所有内容很好地重新打包到 $scope 中,以便视图层可以轻松访问系统并可以执行诸如 ng-repeat= 之类的操作外部 ng-repeat="subscription in subscriptions" 中的“item in subscription.subscription_items”。

从概念上讲,这是有道理的,我已经想到了几种加载此链接数据的方法,但我很好奇的是:这里的最佳做法是什么?我不想过度重新加载数据,所以看起来像一个普通的旧函数,每次我查看一个项目时都会执行一个 REST 请求是一个坏主意,但同时,我不想只是推送数据一次,然后错过了对项目的更新。

所以,问题是:处理这样的链接资源的最佳方法是什么,以符合 $scope 和 $apply 循环中嵌入的想法的方式将 hasMany 和 belongsTo 类型的连接追踪到其他模型?

【问题讨论】:

    标签: angularjs ngresource


    【解决方案1】:

    我喜欢使用延迟加载的dataModel 服务,它会缓存结果并返回承诺。界面如下:

    dataModel.getInstitution(institutionId).then(manageTheInstitution);
    

    如果我需要一些像孩子一样的东西,我会这样称呼它:

    dataModel.getStudents(institutionId).then(manageStudents);
    

    在内部,getStudents 看起来像这样:

    function getStudents(institnutionId) {
        var deferred = $q.defer();
    
        getInstitnution(institutionId).then(function(institution) {
            institution.students = Student.query({institutionId: institutionId});
    
            institution.students.$promise.then(function(students) {
                deferred.resolve(students);
            });
        });
    
        return deferred.promise;
    }
    

    这些函数有点复杂。他们缓存结果并且如果它们已经存在就不会再次请求它们......并返回或链接现有的承诺。他们还处理错误。

    通过以这种方式精心设计我的dataModel 服务,我可以管理任何资源嵌套,并且可以优化我的网络请求。到目前为止,我对这种方法非常满意。

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多