定义AngularJS工厂和控制器可以访问的全局函数和属性

Defining global functions and properties accessible by AngularJS factory and controllers

本文关键字:全局 函数 属性 访问 AngularJS 工厂 控制器 定义      更新时间:2023-09-26

我正在开发一个AngularJS应用程序。当抛出错误时,我想对错误进行一些自定义处理。为此,我做了以下操作:

var myApp = angular.module('myApp', []);
myApp.factory('$exceptionHandler', function($rootScope) {
  return function(exception, cause) {
    try {
      console.log('Unhandled error happening in version ' + $rootScope.APP_VERSION);
      console.log('Error happened at ' + $rootScope.getFormattedDateTime());
    } catch (uex1) {
      console.log('Unable to log unhandled exception.');
    }
  };
});
myApp.run(function ($rootScope) {
  $rootScope.APP_VERSION = '1.0';
  $rootScope.getFormattedDateTime = function() {
    return '--';
  };
});

当我运行这段代码时,我得到这个错误。我想我不能将$rootScope添加到工厂声明中。如果是这种情况,我如何定义全局可访问的函数和变量,以便我可以在我的控制器以及从这个工厂访问它们?

非常感谢您提供的任何帮助

你不能把$routeScope注入到工厂中,这不是一个好主意,但是

你能做的最好的事情就是定义一个新的工厂,并像这样定义你的属性:

   app.factory('getAppInfoFactory',function(){
    return{
    getAppVersion:function(){
       return APP_VERSION = '1.0';
      },
    getFormattedDateTime : function() {
         return '--';
     }
 });

然后你可以随时随地使用这个工厂,像这样:

  myApp.factory('$exceptionHandler', function(getAppInfoFactory) {
    return function(exception, cause) {
      try {
        console.log('Unhandled error happening in version ' + getAppInfoFactory.getAppVersion());
        console.log('Error happened at ' + getAppInfoFactory.getAppInfoFactory());
      } catch (uex1) {
        console.log('Unable to log unhandled exception.');
      }
    };
  });

这绝对是最干净的方法。您可以很容易地用做同样事情的服务替换掉$filter,但是,我发现这种方法更简洁,因为它可以传递任意日期。

下面是演示下面代码的plunkr(Plunkr还包括一些奇特的记录错误的方法):http://plnkr.co/edit/iPMFTJ

angular
  .module('app', [])
  .constant({ APP_VERSION: '1.0' })
  .config(function ($provide) {
    function exceptionHandler($delegate, $filter, $log, APP_VERSION) {
      return function handleException(exception, cause) {
        var formatDateTime = $filter('formatDateTime');
        try {
          $log.error('Unhandled error happening in version ' + APP_VERSION);
          $log.warn('Error happened at ' + formatDateTime(new Date()));
        } catch (uex1) {
          $log.info('Unable to log unhandled exception.');
        }
        // Include the line below if you want angular's default exception
        // handler to run as well
        // $delegate(exception, cause);
      };
    }
    $provide.decorator("$exceptionHandler", exceptionHandler);
  });
angular
  .module('app')
  .filter('formatDateTime', function formatDateTimeFilter($filter) {
    return function formatDateTime(date) {
      return $filter('date')(date, 'shortDate');
    };
  })
  .controller('ErrorCtrl', function () {
    throw new Error('testError');
  });