在 Angular UI 路由器中未解析数据时的错误处理

Error handling when data is not resolved in Angular UI router

我正在使用 angular-ui-路由器的 resolve 在移动状态之前从服务器获取数据。如果请求失败,我想通知用户。我的服务会响应请求失败的错误。我的问题是如何检测 ui-router resolve 中的故障并触发一些模态服务,如弹出窗口。

我在网上看了一些相关的帖子,但我仍然很困惑如何实现它。提前致谢!

配置和服务:

angular.module('myApp',['ui.router', 'ngAnimate', 'ui.bootstrap'])
  .config(function ($stateProvider, $locationProvider) {  
      $locationProvider.html5Mode(true);
      $stateProvider
          .state('customer', {
              url: '/customer',
              templateUrl: '/customer.html',
              controller: 'CustomerCtrl',
              resolve: {
                  /* 
                   * How to inject CustomerService here
                   * How to catch the server error
                   * How to trigger a popup
                   */
                  data: cusomter_data
              }
           });

  })
  .service('CustomerService', function($http, $q) {
      return ({
          getGeneral: getGeneral
      });

      function getGeneral(customer_id) {
          var request = $http({
              method: "get",
                  url: '/customer',
                  params: {
                      customer_id: customer_id
                  }
          });
          return (request.then( handleSuccess, handleError));
      }

      function handleError (response){
          if (!angular.isObject(response.data) || !response.data.message) {
              return($q.reject("Failed to retrieve customer information."));
          } 
          return($q.reject(response.data.message));
      }

      function handleSuccess(response) {
          return (response.data);
      }
  });

经过一番研究,我找到了一个解决方案,方法是创建一个errorModal服务并注入它来解决。这是我的解决方案。

$stateProvider
    .state('customer', {
        url: '/customer',
        templateUrl: '/customer.html',
        controller: 'CustomerCtrl',
        resolve: {
            data: function(CustomerService, SelectedCustomerService, errorModalService) {
                var shared = SelectedCustomerService;
                return CustomerService.getData(shared.customerid).then(
                    function (data) { return data; }, 
                    function(error) { 
                        var modalOptions = {
                            closeButtonText: 'Close',
                            headerText: 'Customer Error',
                            bodyText: error
                        };
                        errorModalService.showModal({}, modalOptions);
                    }
                );
            }
        }
     });