[英]Difference between Testbed.inject(serviceName) and fixture.debugElement.injector.get(serviceName) in Angular Unit Testing
I was going through the test cases written by my team members.我正在浏览我的团队成员编写的测试用例。 What I observed was at some places they've used TestBed.inject(serviceName) for injecting the service and at some places they've used fixture.debugElement.injector.get(serviceName) .
我观察到的是在某些地方他们使用TestBed.inject(serviceName)来注入服务,在某些地方他们使用了 fixture.debugElement.injector.get (serviceName) 。 Can somebody tell me the difference between these two?
有人能告诉我这两者的区别吗? Also what is the correct way of injecting services?
还有什么是注入服务的正确方法?
For eg:例如:
let abc: ABCService让 abc: ABCService
Technique 1: abc = TestBed.inject(ABCService) Technique 2: abc = fixture.debugElement.injector.get(ABCSerice)技术 1:abc = TestBed.inject(ABCService) 技术 2:abc = fixture.debugElement.injector.get(ABCSerice)
Thanks in Advance提前致谢
I think they are essentially the same thing.我认为它们本质上是一样的。 I only use
Technique 1
.我只使用
Technique 1
。
In older versions of Angular, it was TestBed.get
but now it is TestBed.inject
.在旧版本的 Angular 中,它是
TestBed.get
但现在是TestBed.inject
。
I think TestBed.inject
gets the service from the root injector while fixture.debugElement.injector.get
gets the service that is actually injected into the component.我认为
TestBed.inject
从根注入器获取服务,而fixture.debugElement.injector.get
获取实际注入组件的服务。
You can read more about it here .你可以在这里阅读更多关于它的信息。
You can provider a service in the Component
decorator of a Component
and each instance of this service will be unique (a separate instance) and I bet fixture.debugElement.inject.get
will get this unique instance provided in the decorator as opposed to the global singleton.您可以在
Component
的Component
装饰器中提供服务,并且该服务的每个实例都是唯一的(一个单独的实例),我敢打赌, fixture.debugElement.inject.get
将获得装饰器中提供的这个唯一实例,而不是全局singleton。 Check out providers in decorators here .在此处查看装饰器中的提供程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.