【问题标题】:AngularJS load data from serverAngularJS 从服务器加载数据
【发布时间】:2015-01-17 08:26:01
【问题描述】:

我有以下场景,一个页面将显示具有不同数据的不同小部件,后端是带有 SQL Server 和 EF + Repository Pattern + Unit Of Work 的 ASp.NET Web API 2。

如果我必须在小部件信息之上显示一些数据,包括用户个人资料和其他信息,你会推荐什么:

  • 发出一个大的 $​​http.get 请求,该请求将返回一个大的 json 并将其绑定到 UI

  • 每个控制器(服务)在加载时都会对后端进行唯一调用并获取它需要显示的数据,这意味着每个小部件都会调用后端并检索其值。

我只是想知道您推荐的最佳做法是什么。

【问题讨论】:

  • 你知道单个请求有多少 kb 与多个请求的大小相比吗?
  • 无论性能如何,我都会做任何有意义的事情。如果它最终成为性能瓶颈,那么请担心对其进行优化。 “过早的优化是万恶之源”——Donald Knuth

标签: angularjs angularjs-ng-repeat angularjs-service


【解决方案1】:

我认为这取决于...

如果性能可能是一个问题,您应该考虑什么对您的用户最有利...发出 4 个 HTTP 请求的开销是否会影响用户体验?另外,一个大请求会花费太多时间从数据库中检索信息吗?

但是,如果您只想从开发人员的角度来看待问题,我宁愿进行 1 次通用 API 调用,然后在 Angular 中使用不同的参数为每个 Widget 调用 4 次。

【讨论】:

    【解决方案2】:

    发出 4 个请求实际上可能会更快。更不用说数据可以在返回时开始在屏幕上填充,而无需等待最慢的服务。

    求最大并发AJAX请求数http://www.coderanch.com/t/631345/blogs/Maximum-concurrent-connection-domain-browsers

    【讨论】:

      【解决方案3】:

      恕我直言,最好的方法是将每个请求分成单个服务方法,这样您就可以仅重用其中的一部分而不是通过服务器调用来加载整个数据,请检查 angular-resource $resource 以获得干净的可重用服务器调用服务而不是一堆 $https arround 您的代码:

      示例: 指向后端服务器的一些 url 的服务

      .factory('ClientService', ['$resource', function($resource){
              return $resource('http://some_url/:controller/:method', null, {
                  "agents": { method: 'GET', params: { controller: 'agent', method: 'search' }, cache: false },
                  "query": { method: 'GET', params: { controller: 'client', method: 'search' }, cache: false },
                  "save": { method: 'POST', params: { controller: 'client', method: 'save' } },
                  "delete": { method: 'POST', params: { controller: 'client', method: 'delete' } }
              })
      }])
      

      在控制器中的使用(注入ClientService作为依赖)

      // If i want to query the agents into a scope element
      // that will call the url = http://some_url/agent/search
      $scope.agents = ClientService.agents(); 
      // If i want to query a single client i cant send adtional params
      // as is a get request it will call http://some_url/client/search?id=5
      $scope.client = ClientService.query({id:5});
      // and you can event manage callbacks if you want to
      // This will send the client object to the url = http://some_url/client/save
      ClientService.save($scope.client).$promise.then(function(response){ alert(response) })
      

      如您所见,您可以从后端服务器仅访问您需要的内容,如果您不需要,则无需执行所有回调响应,并且以可重复使用的更简洁方式

      信息Angular Resource Docs

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多