如何在服务中注入文件? [英] How to inject Document in service?

查看:97
本文介绍了如何在服务中注入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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服务" rel = "noreferrer">使用内部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屋!

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