如何在服务中注入文件? [英] 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 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.
您可以使用@angular/common
软件包提供的 DOCUMENT
常量.
You can use the DOCUMENT
constant provided by the @angular/common
package.
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屋!