30秒学会 Angular 片段 · 2020年5月13日

30秒学会 Angular 片段 – Injecting document

Sometimes you need to get access to global document.

To simplify unit-testing, Angular provides it through dependency injection:

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

@Component({
  selector: 'my-app',
  template: `<h1>Edit me </h1>`
})
export class AppComponent {

  constructor(@Inject(DOCUMENT) private document: Document) {
    // Word with document.location, or other things here....
  }
}

file:app.component.ts


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

@Component({
  selector: 'my-app',
  template: `<h1>Edit me </h1>`
})
export class AppComponent {
  constructor(@Inject(DOCUMENT) private document: Document) {
    // Don't do this in prod!
    document.body.style.backgroundColor = 'pink';
  }
}

翻译自:https://www.30secondsofcode.org/angular/s/injecting-document

相关链接