gpt4 book ai didi

AngularJS 从服务器加载数据

转载 作者:行者123 更新时间:2023-12-02 23:25:27 25 4
gpt4 key购买 nike

我有以下场景,一个页面将显示具有不同数据的不同小部件,后端是带有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com