简体   繁体   English

定义AngularJS工厂和控制器可访问的全局功能和属性

[英]Defining global functions and properties accessible by AngularJS factory and controllers

I'm working on an AngularJS app. 我正在开发AngularJS应用。 When an error is thrown, I want to do some custom handling of the error. 引发错误时,我想对错误进行一些自定义处理。 To do that, I've done the following: 为此,我做了以下工作:

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 '--';
  };
});

When I run this code, I get this error . 运行此代码时,出现此错误 I guess I can't add $rootScope to factory declarations. 我想我不能将$rootScope添加到工厂声明中。 If that's the case, how do I define globally accessible functions and variables so that I can access them in my controllers as well as from this factory? 如果是这样,如何定义全局可访问的函数和变量,以便可以在我的控制器中以及从该工厂访问它们?

Thank you so much for any assistance you can provide. 非常感谢您提供的任何帮助。

You cant inject $routeScope into a factory , and this is not a good idea However 您不能将$ routeScope注入工厂,但这不是一个好主意。

The best you can do is to define a new factory , and define your property into that factoy like this : 最好的办法是定义一个新工厂,并将属性定义到该工厂中,如下所示:

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

And then you can simply use this factory whenever/whereever you want , like this : 然后,您可以随时随地使用此工厂,就像这样:

  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.');
      }
    };
  });

This would definitely be the cleanest approach. 这绝对是最干净的方法。 You could easily swap out the $filter with a service that does the same thing, however, I find this approach cleaner as it can be passed arbitrary dates. 您可以轻松地将$ filter替换为具有相同功能的服务,但是,我发现这种方法更干净,因为它可以传递任意日期。

Here is a plunkr that demonstrates the code below (Plunkr also includes some fancy ways of logging errors): http://plnkr.co/edit/iPMFTJ 这是一个演示下面代码的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');
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM