问题
My intention is to create print module as detailed in this article. I am getting following error while loading my 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; }
}
Could you please let me know what change I have to make it work?
回答1:
You named your service printServive
instead of printService
. So the service can't be found so calling a property on that undefined property causes this error.
来源:https://stackoverflow.com/questions/56603146/service-property-is-not-accessible-in-component-html