Cómo inyectar el documento en el servicio Angular 2


Tengo una aplicación Angular2. Para burlarse del objeto Document en las pruebas, me gustaría inyectarlo al servicio como:

import { Document } from '??' 

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

El servicio Title de angular utiliza el método interno getDOM():

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

¿Hay alguna forma sencilla de inyectar el documento al servicio? Además, ¿cómo debo referenciarlo en la matriz de proveedores?

Author: RJo, 2016-05-30

3 answers

Esto es soportado directamente en Angular desde hace un tiempo

Https://angular.io/api/common/DOCUMENT

Mi servicio.ts:

import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';

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

Mi servicio.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
  ]));

  ...
});
 45
Author: Günter Zöchbauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-27 06:50:44

No puedo comentar directamente la pregunta de adamdport (todavía no 50 puntos de rep), pero aquí está como se indica en los documentos de angular.

Blockquote @GünterZöchbauer parece que el DOCUMENTO está en desuso. ¿Alguna idea de cómo hacer esto una vez que se ha ido? Por ejemplo, ¿cómo establecería el favicon dinámicamente?

En lugar de importar desde el navegador de la plataforma de esta manera:

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

Impórtalo desde angular common:

import {DOCUMENT} from '@angular/common';
 20
Author: Ruud Voost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-02 11:39:07

Además de la respuesta de @Günter Zöchbauer.

Angular definir DOCUMENTO como un InjectionToken

export const DOCUMENT = new InjectionToken<Document>('DocumentToken');

Dom_tokens.ts

E inyectarlo con el documento en el navegador .ts

{provide: DOCUMENT, useFactory: _document, deps: []}


export function _document(): any {
  return document;
}

Por lo tanto, cuando lo usamos, solo necesitamos inyectar @Inject(DOCUMENT)

O utilice el token directamente en deps:[DOCUMENT]

 7
Author: maxisam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-02 17:44:13