在 component.html 中无法访问服务 属性
Service property is not accessible in component.html
我的目的是创建此 article 中详述的打印模块。
加载 app.component.html:
时出现以下错误
AppComponent.html:1 ERROR TypeError: Cannot read property 'isPrinting' of undefined
App.component.html
<div [class.isPrinting]= "printService.isPrinting">
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<button (click) ="onPrintReport()"> Print Report</button>
<router-outlet name='print"'></router-outlet>
</div>
</div>
App.component.ts
import { Component } from '@angular/core';
import {PrintService} from './print.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'printer';
constructor(public printServive: PrintService) {
//console.log("Print:", this.printServive.isPrinting);
}
}
print.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class PrintService{
isPrinting = false;
constructor(private router: Router) {}
}
Style.css
/* You can add global styles to this file, and also import other style files */
@media print {
.isPrinting > * { display: none; }
.isPrinting app-print-layout { display: block; }
}
能否请您告诉我需要做哪些更改才能使其正常工作?
您将服务命名为 printServive
而不是 printService
。因此无法找到该服务,因此在未定义的 属性 上调用 属性 会导致此错误。
我的目的是创建此 article 中详述的打印模块。 加载 app.component.html:
时出现以下错误AppComponent.html:1 ERROR TypeError: Cannot read property 'isPrinting' of undefined
App.component.html
<div [class.isPrinting]= "printService.isPrinting">
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<button (click) ="onPrintReport()"> Print Report</button>
<router-outlet name='print"'></router-outlet>
</div>
</div>
App.component.ts
import { Component } from '@angular/core';
import {PrintService} from './print.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'printer';
constructor(public printServive: PrintService) {
//console.log("Print:", this.printServive.isPrinting);
}
}
print.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class PrintService{
isPrinting = false;
constructor(private router: Router) {}
}
Style.css
/* You can add global styles to this file, and also import other style files */
@media print {
.isPrinting > * { display: none; }
.isPrinting app-print-layout { display: block; }
}
能否请您告诉我需要做哪些更改才能使其正常工作?
您将服务命名为 printServive
而不是 printService
。因此无法找到该服务,因此在未定义的 属性 上调用 属性 会导致此错误。