1

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

假设我有一个ProjectService. 理想情况下,如果有一个方法被调用getAllProjects,它将返回一个项目数组。但是那样我不知道服务器通信发生了什么。

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

谢谢。

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 ...

    }
  };

});
4

1 回答 1

0

在我们的代码库中,我们一直在做

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

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

但是,假设您想这样做,我可以想到几种方法。假设您和我们一样,将您的旗帜放在一个对象中。然后,您可以利用关联来发挥自己的优势:

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

通过将引用建立为服务的属性,您可以在服务内进行所有状态切换,并避免弄乱您的控制器。尽管如此,这可能会产生两个或多个靠近在一起的查询冲突的可能缺点(第一个查询完成并在第二个查询完成之前删除加载状态)。

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

于 2012-09-25T00:40:00.670 回答