从JavaScript代码获取对Angular服务实例的访问 [英] Get access to Angular service instance from JavaScript code

查看:52
本文介绍了从JavaScript代码获取对Angular服务实例的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是基于Angular服务中的数据进行一些测试断言,即我们正在尝试创建E2E测试,并且所使用的工具允许我们对断言执行任意的JavaScript代码,因此,我需要知道是否可以访问Angular服务实例.

What I'm trying to do is have some testing assertions based on the data in the Angular service, i.e. we're trying to create E2E tests and the tool we're using allows us to execute arbitrary JavaScript code for assertions, so for that I need to know if it's possible to get access to the Angular service instance.

如何从普通的JS代码访问Angular服务实例?

How can I get access to an Angular service instance from plain JS code?

也就是说,如果部署了Angular应用程序,并且在浏览器中打开了该应用程序,然后打开Chrome DevTools,是否可以访问已提供给所有组件的Angular服务的服务实例?

That is, if my Angular app is deployed, and I open the app in the browser, then open Chrome DevTools, can I get access to the service instance of the my Angular service that was provided to all components?

我知道可以通过 ng.probe($ 0)等访问您的组件,但是不确定服务.

I know it's possible to get access to your component by through ng.probe($0) etc. but not sure about services.

从到目前为止的搜索来看,似乎我们必须使用 Injector 类,然后使用它的 .get()方法来访问一个Angular服务实例,但是我不确定如何访问 Injector 类/实例本身?

From what I have searched so far, it seems like we have to do use the Injector class and then use it's .get() method to get access to one of the Angular service instances but I'm not sure how would I get access to the Injector class/instance itself?

这是我尝试的方法: ng.probe($ 0)( $ 0 是我应用程序的< app-root> )和然后我看到返回值具有 .injector 属性,我尝试调用 ng.probe($ 0).injector.get('MyServiceName')并收到错误对于:未捕获的错误:MyServiceName没有提供者!.

Here's what I tried: ng.probe($0) ($0 being the <app-root> of my app) and then I see that the return value has an .injector property, I tried to call ng.probe($0).injector.get('MyServiceName') and got an error for: Uncaught Error: No provider for MyServiceName!.

(即使我在上面尝试 ng.probe ,我也很想知道如何在不使用ng.probe的情况下访问注射器,因为在执行自动测试(即prod模式)期间,我不要以为我可以做 ng.probe($ 0))

(Even though I'm trying ng.probe above, I would love to know how to get access to the injector without ng.probe because during execution of the automated testing i.e. prod mode, I don't think I'll be able to do ng.probe($0))

因此,我不确定是否要尝试以正确的方式访问它?有什么想法吗?

So I'm not sure if I'm trying to access it the right way? Any ideas?

我正在使用Angular 4.

I'm using Angular 4.

推荐答案

在Angular 7中,我可以使用 ng.probe():

This works for me in Angular 7 using ng.probe():

window.ng.probe(window.getAllAngularRootElements()[0]).injector.view.root.ngModule._providers.find(p => p& p.constructor&& p.constructor.name ==='MyServiceName');

我想如果没有 ng.probe()

这篇关于从JavaScript代码获取对Angular服务实例的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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