加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – 如何在Angular 2服务中注入文档

发布时间:2020-12-17 07:39:06 所属栏目:安全 来源:网络整理
导读:我有一个Angular2应用程序.为了在测试中嘲笑Document对象,我想将其注入到服务中,如: import { Document } from '??' @Injectable()export class MyService { constructor(document: Document) {}} 角度的Title服务使用内部的getDOM()方法: https://github.
我有一个Angular2应用程序.为了在测试中嘲笑Document对象,我想将其注入到服务中,如:
import { Document } from '??' 

@Injectable()
export class MyService {
  constructor(document: Document) {}
}

角度的Title服务使用内部的getDOM()方法:

https://github.com/angular/angular/blob/master/modules/%40angular/platform-browser/src/browser/title.ts

有没有简单的方式将文档注入到服务中?此外,我应该如何在provider数组中引用它?

bootstrap(provide(Document,{useClass: MyDocumentImpl})

其中Document是@angular/platform-browser/src/dom/dom_tokens.ts的文件

@angular/platform-browser出口

最后的例子

基于Angular的DomRenderer does it的例子.

我-service.ts:

import { Inject,Injectable} from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class MyService {
  constructor(@Inject(DOCUMENT) private document: any) {}
}

我-service.spec.ts

import { provide } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

import { MyService } from './my-service';

class MockDocument {}

describe('MyService',() => {
  beforeEachProviders(() => ([
    provide(DOCUMENT,{ useClass: MockDocument }),MyService
  ]));

  ...
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读