Angular 在另一个组件中使用布尔变量
我从TypeScript开始,在component home.component.ts中有一个布尔displayReport变量。我想在另一个组件系列list.component.ts中获取此变量的值Angular 在另一个组件中使用布尔变量,angular,typescript,Angular,Typescript,我从TypeScript开始,在component home.component.ts中有一个布尔displayReport变量。我想在另一个组件系列list.component.ts中获取此变量的值 public displayReport: boolean = false; public viewReport(): void { console.log(this.displayReport); this.displayReport = !this.displayReport; } 可能吗
public displayReport: boolean = false;
public viewReport(): void {
console.log(this.displayReport);
this.displayReport = !this.displayReport;
}
可能吗
///////////////////////////////编辑//////
以下是我所做的:
在home.component.ts组件中:
constructor(
private studyService: StudyService
){}
}
在series-list.component.ts组件中:
constructor(
private studyService: StudyService
构造函数(专用studyService:studyService){
}
在service study.service.ts中:
public displayReport: boolean = false;
但当我在series-list.component.html中执行此操作时:
<div *ngIf="this.studyService.displayReport"> </div>
我没有获取此.studyService.displayReport变量的值。我有这个错误:未解析变量studyService
我该怎么做?要在组件之间共享值或方法,您需要创建一个
服务,例如report.service.ts
,该服务共享报告,以在注入报告的组件中显示和传播报告
以下是有关angular services的官方文档:要在组件之间共享值或方法,您需要创建一个服务
,例如,共享报告的report.service.ts
,以在注入的组件中显示和传播报告
以下是有关角度服务的官方文档:
- 如果
您的组件是子组件,您可以使用@Input()传递它
只需在子组件中声明@Input变量并在
你叫它李>
- 否则
您可以将服务用作中间件,并在模块的提供程序中声明您的服务,它将作为单例对象工作
- 如果
您的组件是子组件,您可以使用@Input()传递它
只需在子组件中声明@Input变量并在
你叫它李>
- 否则
您可以将服务用作中间件,并在模块的提供程序中声明您的服务,它将作为单例对象工作
在编辑部分之后回答您的问题。去掉html中的“this.”。您可能还需要公开服务,以便从html中引用它(但不确定)。在编辑部分之后回答您的问题。去掉html中的“this.”。您可能还需要将服务公开,以便从html中引用它(但不确定)。如果这些组件不相关,请使用服务:@AJT R 82我编辑了我的帖子。您的代码应该可以正常工作(只是尝试过),请确保该服务仅在应用程序模块级别提供,而不是在组件提供程序中提供array@AJT_82我试过。。当我在html series-list.component.html中时,他不知道这项服务。但是在series-list.component.ts中,我将其初始化为:
import{StudyService}from./study/study.service”;导出类SeriesListComponent{constructor(private studyService:studyService){}
我重新打开了这个问题。请提供足够的代码来重现此问题,最好是您可以创建一个演示。如果这些组件不相关,请使用服务:@AJT_82我编辑了我的帖子。您的代码应该可以正常工作(刚刚尝试过),请确保该服务仅在应用程序模块级别提供,而不是在组件提供程序中提供array@AJT_82我试过。。当我在html series-list.component.html中时,他不知道这项服务。但是在series-list.component.ts中,我将其初始化为:import{StudyService}from./study/study.service”;导出类SeriesListComponent{constructor(private studyService:studyService){}
我重新打开了这个问题。请提供足够的代码来重现这个问题,最好是你能创建一个演示。