在 component.html 中无法访问服务属性 [英] Service property is not accessible in component.html
本文介绍了在 component.html 中无法访问服务属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目的是创建此文章中详述的打印模块.加载 app.component.html 时出现以下错误:
AppComponent.html:1 错误类型错误:无法读取未定义的属性isPrinting"
App.component.html
<div style="text-align:center"><h1>欢迎来到{{title}}!<按钮(点击)="onPrintReport()">打印报告按钮><router-outlet name='print"'></router-outlet>
App.component.ts
import { Component } from '@angular/core';从 './print.service' 导入 {PrintService};@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {title = '打印机';构造函数(公共打印服务:打印服务){//console.log("Print:", this.printServive.isPrinting);}}
print.service.ts
import { Injectable } from '@angular/core';从@angular/router"导入{路由器};@Injectable({提供在:'根'})导出类 PrintService{isPrinting = false;构造函数(私有路由器:路由器){}}
Style.css
/* 你可以在这个文件中添加全局样式,也可以导入其他样式文件 */@媒体打印{.isPrinting >* { 显示:无;}.isPrinting app-print-layout { display: block;}}
能否请您告诉我需要进行哪些更改才能使其正常工作?
解决方案
您将服务命名为 printServive
而不是 printService
.因此无法找到该服务,因此调用该未定义属性上的属性会导致此错误.
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?
解决方案
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.
这篇关于在 component.html 中无法访问服务属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文