AngularJS 从服务器加载数据

标签 angularjs angularjs-ng-repeat angularjs-service

我有以下场景,一个页面将显示具有不同数据的不同小部件,后端是带有 SQL Server 和 EF + 存储库模式 + 工作单元的 ASp.NET Web API 2。

如果我必须显示相当多的数据,包括用户个人资料和小部件信息之上的其他信息,您会推荐什么:

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

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

我只是想知道您推荐什么最佳实践。

enter image description here

最佳答案

恕我直言,最好的方法是将每个请求分成单个服务方法,这样您就可以重用其中的一部分,而不是进行服务器调用来加载整个数据,请检查 Angular 资源$resource 拥有一个干净的可重用的服务器调用服务,而不是一堆 $https 围绕您的代码:

示例: 指向后端服务器某些 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' } }
        })
}])

在 Controller 中的使用(注入(inject)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

关于AngularJS 从服务器加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27023285/

相关文章:

javascript - AngularUi jQuery Passthrough - 调用方法获取插件值

javascript - 设计 AngularJS 服务的更好方法

javascript - 在 Angular 中的 Controller 之间共享数据,观看还是不观看?

javascript - ng-repeat 检测第一次出现的条件

angularjs - 如何在angularjs中一个一个地列出名字

javascript - ng-repeat 键值对象上的自定义过滤器仅更新 View 2 次

javascript - Angularjs 工厂返回什么?

javascript - 使用 angular.bootstrap() 时 AngularJs Unknown provider 错误

javascript - 解决 MainController 的 promise

java - 使用 Spring MVC 和 AngularJS 的方法 DELETE