【问题标题】:Service property is not accessible in component.html在 component.html 中无法访问服务属性
【发布时间】:2025-12-15 13:20:03
【问题描述】:

我的意图是创建此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; }
  }

能否请您告诉我必须进行哪些更改才能使其正常工作?

【问题讨论】:

  • 小错字,关闭你的问题
  • @Sajeetharan 感谢您的推荐。得到丹尼斯的回答,我觉得拒绝他的努力是不公平的。你介意我保留这个问题吗?
  • 我想它无论如何都会被关闭

标签: angular angular7 angular7-router


【解决方案1】:

您将服务命名为 printServive 而不是 printService。因此无法找到该服务,因此调用该未定义属性的属性会导致此错误。

【讨论】: