簡體   English   中英

定義AngularJS工廠和控制器可訪問的全局功能和屬性

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

我正在開發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');
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM