gpt4 book ai didi

javascript - 如何让我的 Controller 知道加载数据的状态?

转载 作者:行者123 更新时间:2023-11-28 09:39:23 25 4
gpt4 key购买 nike

我正在开发一个大型 AngularJS 应用程序,在其中我试图将所有 Ajax 代码封装到 Controller 从中获取数据的各种服务中。问题在于需要了解任何 ajax 调用的状态并向用户显示正确的信息。可能未找到数据、当前正在加载数据或发生阻止数据加载的错误。需要向用户显示加载消息、“未找到数据”消息或错误消息。

假设我有一个 ProjectService。理想情况下,如果有一个名为 getAllProjects 的方法,它将返回一个项目数组。但这样我就不知道服务器通信发生了什么。

那么我如何让 Controller 知道数据是否已加载、正在加载或发生错误?我能想到的最好方法是使用回调,如下面的伪代码所示。有没有更好的方法来完成这样的事情或我可能忽略的事情?

谢谢。

app.controller( "ProjectController", function( $scope, ProjectService ){

// Set the initial / default status
$scope.loadStatus = "loading";

// Return an empty array initially that will be filled with
// any data that is returned from the server
// The callback function will be executed when the ajax call is finished
$scope.projects = ProjectService.getProjects(function( status ){

// Alert the controller of a status change
setStatus( status );

});

function setStatus( ){
$scope.loadStatus = status;

// ... update the view or whatever is needed when the status changes....
}

});

app.service( "ProjectService", function( $resource ){

return {
getAllProjects: function(){

// ... load and return the data from the server ...

}
};

});

最佳答案

在我们的代码库中,我们刚刚做了

$scope.flags.loading = true;
$http(...).success(function(){
$scope.flags.loading = false;
});

是的,这有点简单,但并非所有查询都需要加载覆盖(例如在分页或刷新期间)。这就是为什么我们选择不简单地使用装饰器。

但是,假设您愿意,我可以想出几种方法来做到这一点。假设您像我们一样,将您的标志放在一个对象中。然后你就可以利用关联来发挥你的优势:

MyService.flags = $scope.flags
... (inside the service) ...
this.flags.loading = true/false;

通过将引用建立为服务的属性,您可以在服务内执行所有状态切换,并避免 Controller 困惑。不过,这可能会造成两个或多个紧密相连的查询发生冲突的可能缺点(第一个查询完成并在第二个查询完成之前删除加载状态)。

出于这个原因,我们发现设置了标志。我们并不真正检查“已加载”,我们只是检查数据或使用成功回调。

关于javascript - 如何让我的 Controller 知道加载数据的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12573996/

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