如何在服务中注入文档? [英] How to inject Document in service?
问题描述
我有一个 Angular 2 应用程序.为了在测试中模拟 Document
对象,我想将它注入到服务中,例如:
I have an Angular 2 application. For mocking the Document
object in tests, I'd like to inject it to the service like:
import { Document } from '??'
@Injectable()
export class MyService {
constructor(document: Document) {}
}
Angular 的 Title
服务 使用内部 getDOM()
方法.
The Title
service of Angular uses the internal getDOM()
method.
有没有什么简单的方法可以将 Document
注入到服务中?另外,我应该如何在 providers
数组中引用它?
Is there any simple way to inject the Document
to the service? Also, how should I reference it in the providers
array?
推荐答案
Angular 已经支持了一段时间.
This has been supported by Angular for a while.
您可以使用提供的
包.DOCUMENT
常量>@angular/common
DOCUMENT
常量的描述(取自 API 文档):
Description of the DOCUMENT
constant (taken from the API documentation):
代表主要渲染上下文的 DI 令牌.在浏览器中,这是 DOM 文档.
A DI Token representing the main rendering context. In a browser, this is the DOM Document.
一个例子如下所示:
import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Injectable()
export class MyService {
constructor(@Inject(DOCUMENT) private document: Document) {}
}
my-service.service.spec.ts
import { provide } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { MyService } from './my-service';
class MockDocument {}
describe('MyService', () => {
beforeEachProviders(() => ([
provide(DOCUMENT, { useClass: MockDocument }),
MyService
]));
...
});
这篇关于如何在服务中注入文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!