javascript - 如何为可以在控制台中检查的 Angular 服务创建变量?

标签 javascript angularjs debugging

我有一个基于核心服务的 Angular 应用程序。

为了简化调试,我宁愿不必记住以下调用(来自 how to debug angular services in browser ):

tasks = angular.element(document.body).injector().get('tasks');

所以我的第一个想法是将此语句粘贴在我的index.html 中的脚本标记中,但如果我这样做,它会失败

Uncaught TypeError: Cannot read property 'get' of undefined

我一直在寻找 jQuery 文档的等效项,但似乎这不是 Angular 的方式。 Angular 方式似乎是这样的构造(来自 https://plus.google.com/+MicahGodbolt/posts/CiKyN2YUafM ):

angular.module('mushin', []).run(function() {
  window.tasks = angular.element(document.body).injector().get('tasks');
})

但这给了我同样的错误。

将 Angular 服务放入 JavaScript 变量以在控制台中进行调试的正确方法是什么?

最佳答案

您可以在任何使用tasks 服务的地方将其附加到widow 对象。在上面使用 run() 方法的示例中,您只需将 tasks 服务添加为函数的依赖项,如下所示:

angular.module('mushin', []).run(function(tasks) {
  window.tasks = tasks;
});

它现在失败了,因为在 run 方法的入口处,还没有任何东西绑定(bind)到 body 元素,所以你还没有注入(inject)器。

执行此操作的更“Angular 方式”是还依赖于 $window 服务,因此您的回调将变为:

angular.module('mushin', []).run(function($window, tasks) {
  $window.tasks = tasks;
});

关于javascript - 如何为可以在控制台中检查的 Angular 服务创建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25194839/

相关文章:

javascript - 未找到 HTML 文档的字符编码声明

javascript - 如何在 knex.js 中加入外部表条目的计数?

javascript - 在 angular.foreach 循环中重置数组值

angularjs - 如何防止错误 : [ng:btstrpd] App Already Bootstrapped with this Element 'document'

debugging - 如何在 Debug模式下运行 gulp-nodemod?

javascript - 其他人创建的 Firebase 用户

javascript - Chart.js 中的随机填充颜色

javascript - 在集成 Google Plus 的同时,如何在 Angular JS 中使用 google Oauth 接收刷新 token

c++ - 在 std::vector 中存储 __m256i 仅在 Release模式下产生访问冲突

wcf - 为什么我的模块不在模块列表中?