【问题标题】:Use boolean variable in another component在另一个组件中使用布尔变量
【发布时间】:2017-11-07 21:05:25
【问题描述】:

我从 TypeScript 开始,我在组件 home.component.ts 中有一个布尔值 displayReport 变量。我想在另一个组件 series-list.component.ts 中获取这个变量的值。

public displayReport: boolean = false;

public viewReport(): void {
console.log(this.displayReport);
this.displayReport = !this.displayReport;

}

有可能吗?

//////////////////////////编辑//////////// ////////:

这是我所做的:

在 home.component.ts 组件中:

constructor(
private studyService: StudyService

) { }

public viewReport(): void {
console.log('displayReport : ' + this.studyService.displayReport);
this.studyService.displayReport = !this.studyService.displayReport;

}

在 series-list.component.ts 组件中:

构造函数(私人学习服务:StudyService){ }

在服务 study.service.ts 中:

public displayReport: boolean = false;

但是当我在 series-list.component.html 中这样做时:

<div *ngIf="this.studyService.displayReport"> </div>

我没有得到 this.studyService.displayReport 变量的值。我有这个错误:Unresolved variable studyService

我该怎么办?

【问题讨论】:

  • 如果这些组件不相关,请使用服务:stackoverflow.com/a/40539061/6294072
  • @AJT_82 我编辑了我的帖子..
  • 您的代码应该可以正常工作(刚刚尝试过),请确保该服务仅在应用模块级别提供,而不是在组件提供程序数组中提供
  • @AJT_82 我试过..当我在html series-list.component.html中时,他不知道这个服务。然而在 series-list.component.ts 我这样初始化它:import {StudyService} from "../study/study.service"; export class SeriesListComponent { constructor (private studyService: StudyService) { } }
  • 我重新打开了这个问题。请提供足够的代码来重现此问题,最好是创建一个演示。

标签: angular typescript


【解决方案1】:

在编辑部分之后回答您的问题。摆脱“这个”。在你的 html 中。您可能还需要公开服务以便从 html 中引用它(虽然不确定)。

【讨论】:

    【解决方案2】:

    要在组件之间共享值或方法,您需要创建一个service,例如report.service.ts,用于共享报告以在注入它的组件中显示和传播。

    这里是关于角度服务的官方文档:https://angular.io/tutorial/toh-pt4

    【讨论】:

      【解决方案3】:
      • 如果 您的组件是子组件,您可以使用 @Input() 传递它 只需在您的子组件中声明 @Input 变量并在同时传递它 你打电话给它。
      • 其他 您可以将服务用作中间件并在模块的提供者中声明您的服务,它将作为单例对象工作

      【讨论】:

        猜你喜欢
        • 2016-07-20
        • 2016-06-14
        • 2014-08-16
        • 2019-05-13
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多