在angular.js应用程序中全局执行错误处理的最佳方法是什么?

时间:2013-11-20 10:03:27

标签: angularjs

我有一个应用程序,它使用我创建的各种服务进行http调用。当服务器请求失败或api返回错误属性时,我想在页面顶部显示这些错误。

我可以在角度文档中看到错误最好以这种方式显示,这是有道理的:

<div ng-controller="AlertDemoCtrl">
  <alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">{{alert.msg}}</alert>
</div>

在AlertDemoCtrl中:

  $scope.addAlert = function() {
    $scope.alerts.push({msg: "Another alert!"});
  };

  $scope.closeAlert = function(index) {
    $scope.alerts.splice(index, 1);
  };

问题是我不确定如何将错误推送到AlertDemoCtrl中的警报,因为http请求发生在我无法访问AlertDemoCtrl的服务中。我是否需要广播事件才能将它们添加到AlertDemoCtrl中,或者是否有办法将控制器注入服务?或者我需要将addAlert函数添加到$ rootScope?

感谢任何建议,谢谢!

1 个答案:

答案 0 :(得分:10)

我实现此方法的方法是使用messageService公开以下界面:

{
    messages:      /* an array of all messages */,
    addMessage:    /* function(severity, text) */,
    removeMessage: /* function(messageObject) */,
    // other stuff, irrelevant to current topic
}

每个消息对象都有一个文本,一个“严重性”(ERROR,WARNING等)和一个删除方法。我还为消息添加了一个超时选项,并自动删除。

任何需要添加消息的控制器都使用messageService。消息控制器将服务的messages属性公开给它的作用域,并将模板ng-repeat公开给它们(我想在页面顶部显示消息)。使用引导样式:

<div id="messageContainer" ng-controller="messages">
    <div alert
         ng-repeat="msg in messages"
         type="msg.severity"
         close="closeMsg($index)"
    >
        {{msg.text}}
    </div>
</div>

控制器:

app.controller("messages", ["$scope", "messageService"],
function($scope, messageService) {
    $scope.messages = messageService.messages,
    $scope.closeMsg = function(index) {
        $scope.messages[index].remove();
    };
});

现在,如果服务需要添加消息,它可以与messageService进行交互。我宁愿没有服务与UI交互;我认为服务返回消息列表以及控制器按照自己的意愿处理它们会更好。