【问题标题】:How to capture the $state object in console from an angular application for debugging purpose?如何从 Angular 应用程序捕获控制台中的 $state 对象以进行调试?
【发布时间】:2017-09-30 16:38:18
【问题描述】:

我想在我的 Angular 应用程序中使用 $state.reload() 进行调试。请参阅此相关问题how-do-i-reload-an-angular-partial-for-testing-purpose

但是,我无法在我的应用程序中捕获$state,它甚至没有暴露$rootScope 对象?我设法通过这样做获得了 $rootScope,如how-to-access-update-rootscope-from-outside-angular

var $body = angular.element(document.body);
var $rootScope = $body.scope().$root; 

然后如Wiki中所述

var myApp = angular.module('myApp', []);
angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

但这并没有对$rootScope.$state 设置任何内容,因为现在可以访问 $rootScope。有什么帮助吗?我正在使用 Angular 1.3.x。

编辑:即使这样也行不通,

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    console.log("Testing");
});

【问题讨论】:

  • 问题是它没有事件run?
  • 最后一个 sn-p 显然因为一些错误而不起作用。如果您遇到问题,总是希望提供完整的错误消息和 stackoverflow.com/help/mcve ,否则解决问题将变成完全的猜测。无论如何,在您的情况下,$rootScope.$state = $state 是不必要的黑客攻击。应该只是angular.element(document.body).injector().get('$state')
  • 好的,我没有看到与此相关的回溯,但正在执行的其他操作失败 - 无法将其与此相关联。但没关系。稍后会调试它。我可以看到run 做了一个push 所以它可能不会同步发生:)

标签: angularjs angular-ui-router


【解决方案1】:

考虑到 AngularJS 应用程序是在 body 上引导的,应该可以使用

angular.element(document.body).injector().get('$state');

没有必要将它暴露给作用域。

【讨论】:

  • 优秀。我一直在寻找这样的解决方案。谢谢。
【解决方案2】:

对于角度 1.5.x - 1.6.x

你需要安装这个https://github.com/olov/ng-annotate,之后你的代码应该是这样的

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    'ngInject'; // this will fix dependency injection
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

【讨论】:

  • 我在这个应用程序中使用 Angular 1.3.x。所以里面什么都做不了?
  • 你需要尝试一下,我认为 ngAnnotate 将适用于 1.3.x
  • 难道我们没有没有附加模块的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多