优雅地处理AngularJS错误:$ injector:nomod模块不可用 [英] Gracefully handling AngularJS Error: $injector:nomod Module Unavailable

查看:1872
本文介绍了优雅地处理AngularJS错误:$ injector:nomod模块不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角度应用取决于第三方角度服务:

My angular app depends on a third-party angular service:

var app = angular.module("ninjaModule", ['angular-google-analytics']);

只要我的广告拦截插件处于关闭状态,应用程序就会正常加载。然而,广告拦截器在角度抛出 $ injector:nomod 错误,无法加载整个应用程序。

The app loads up just fine, as long as my ad-blocking plugins are off. However, with ad-blockers on angular throws an $injector:nomod error, failing to load the whole app.

我正在寻找一种方法来优雅地处理这些错误,因此无论广告拦截器如何,都可以加载应用程序。如果角谷歌分析不会在那里 - 很好,这不是关键,我可以处理它或设置一些后备。但是,整个应用程序崩溃的情况不适合我。任何想法?

I'm looking for a way to gracefully handle these errors, and therefore be able to load the app regardless of ad-blockers. If angular-google-analytics won't be there - fine, it's not critical, I can deal with it or set up some fallback. But a situation where the whole app crashes is not an option for me. Any ideas?

准确地说 - 我不想在广告拦截器上工作,例如通过重命名我的脚本文件。我希望有一个角度尝试抓住魔术。

To be precise - I don't want to work around ad-blockers, e.g. by renaming my script files. I'd expect an angular try-catch magic trick.

Plunker: http://plnkr.co/edit/sbEG6vclPidPSNGV5Bsa

推荐答案

我终于搞定了。不过,该解决方案需要一些窍门:

I finally got it working. The solution requires a few hacks, though:


  1. 检查是否加载了角度谷歌分析

  2. 使用 $ injector

  3. 准备主模块的依赖项列表( deps ) code>而不是 Analytics(分析)显式地

  1. checking if angular-google-analytics is loaded
  2. preparing the dependency list (deps) for the main module on the fly
  3. using $injector instead of Analytics explicitly

配置 AnalyticsProvider ,但对 $ injector 应该相对容易。

Still, I need to configure AnalyticsProvider, but it should be relatively easy to do with $injector.

var deps = [];

try {
  angular.module("angular-google-analytics"); // this throws if GA script is not loaded
  deps.push('angular-google-analytics');
} catch(e){ console.error("GA not available", e); }

angular.module('mainApp', deps)
.run(function($rootScope, $injector) {
  try {
    Analytics = $injector.get('Analytics');
    $rootScope.trackPage = function() {
      console.log('Analytics in action!');
      Analytics.trackPage();
    }
  } catch(e) {
    $rootScope.trackPage = function(key, label) {
      console.log("Fallback in action!")
    }
  }
})
.controller('MyCtrl', function($rootScope, $scope) {
  $scope.message = 'Hello World!';
  $rootScope.trackPage();
});

更新过的邮件: http://plnkr.co/edit/Zo4RgKOybzhvJQdW2nQZ?p=preview

这篇关于优雅地处理AngularJS错误:$ injector:nomod模块不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆