如何从控制台测试 AngularJS 服务? [英] How can I test an AngularJS service from the console?

查看:28
本文介绍了如何从控制台测试 AngularJS 服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的服务:

angular.module('app').factory('ExampleService', function(){
  this.f1 = function(world){
    return 'Hello '+world;
  }
  return this;
})

我想从 JavaScript 控制台测试并调用服务的函数 f1().

I would like to test it from the JavaScript console and call the function f1() of the service.

我该怎么做?

推荐答案

TLDR:在一行中,您要查找的命令:

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

<小时>

深潜

AngularJS 使用依赖注入 (DI) 将服务/工厂注入到您的组件、指令和其他服务中.所以你需要做的是先获取 AngularJS 的注入器(注入器负责连接所有依赖项并将它们提供给组件).


Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

要获取应用的注入器,您需要从 angular 正在处理的元素中获取它.例如,如果您的应用在您调用的 body 元素上注册了 injector = angular.element(document.body).injector()

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

从检索到的 injector 中,您可以使用 injector.get('ServiceName')

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

有关此答案的更多信息:无法从 angular 检索注入器
甚至更多:从旧代码调用 AngularJS

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code

获取特定元素的 $scope 的另一个有用技巧.使用开发者工具的 DOM 检查工具 选择元素,然后运行以下行($0 始终是所选元素):
angular.element($0).scope()

Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

这篇关于如何从控制台测试 AngularJS 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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