javascript - 为什么我的输入变量属性未定义(Angular)
问题描述
我在应用程序组件中从我的服务中获取数据,然后通过@Input 将其传递给子组件。当我在 ngOnInit 中 console.log 数据时,它确实显示在子组件中,但是当我尝试将它传递给变量并在子模板中使用它时,它会返回未定义,我不知道为什么。
这是我在 app.component.ts 中调用我的服务的地方,有问题的数据是 this.colorcounts。ngOnInit 内的控制台日志记录确实显示了正确的数据。colorCounts 有 3 个属性:红色、黄色和绿色:
ngOnInit() {
this.pciService.getPciInfo()
.subscribe((pciInfo) => {
this.spinner.hide();
this.pciData = pciInfo.sorted,
this.colorCounts = pciInfo.counts;
});
这是我将数据向下传递的 app.component.html 模板:
<app-navbar *ngIf="colorCounts" [colorCounts] = "colorCounts"></app-navbar>
<app-system-status [pciData]="pciData"></app-system-status>
这是我正在获取数据的子组件,在 ngOnInit 中执行 console.log 确实有效,但尝试在模板中使用“red”或将其保存在类中返回未定义:
constructor(private pciService: PciService,
public dialog: MatDialog,
private decimalPipe: DecimalPipe) { }
AMVersion: any;
@Input() colorCounts: Colors;
openDialog(): void {
let dialogRef = this.dialog.open(AmVersionDialogComponent, {
panelClass: 'custom-dialog-container',
data: {}
});
(<AmVersionDialogComponent>dialogRef.componentInstance).AMVersion = this.AMVersion;
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
ngOnInit() {
this.pciService.getAMVersion()
.subscribe((AMInfo) => {
return this.AMVersion = AMInfo;
});
var red = this.colorCounts.red;
console.log(red)
console.log(this.colorCounts);
}
}
我知道我可能遗漏了一些关于生命周期的简单内容。有人可以在这里指出我正确的方向吗?
解决方案
所有 Observable 都是异步的,因此在模板*ngIf
条件中将检查变量,如果它为 null 将返回 null 但如果您使用管道变量,因为| async
它将一直检查此变量,并且当变量不显示为 null 时,它将显示内容ngIf
。
*ngIf
只工作一次!!!他不等待 anny http 调用,并且 Observables 正在做一个平常的事情。如果你想*ngIf
等待电话你需要在| async
里面使用管道。
与您订阅它ngOnInit()
并分配给模板中的变量相同。订阅将在模板全部显示在屏幕上之后分配这些值。阅读异步的含义。
您需要知道这是一个样板代码:
ngOnInit() {
this.pciService.getPciInfo()
.subscribe((pciInfo) => {
this.spinner.hide();
this.pciData = pciInfo.sorted,
this.colorCounts = pciInfo.counts;
});
最好这样做:
ngOnInit() {
this.pciInfo$ = this.pciService.getPciInfo()
}
在模板中:
<ng-container *ngIf="pciInfo$ | async as pciInfo">
<app-navbar [colorCounts]="picInfo.counts"></app-navbar>
</ng-container>
Pipe Async 将为您订阅 Observable。
推荐阅读
- css - 是否可以找到导致规则在 Chrome 检查器中显示为灰色的父 CSS?
- node.js - 无法识别的表达式 '$nin' Mongodb
- julia - 尝试在 Windows 上的 Julia 中安装 Pardiso
- c# - C#检测光标是否隐藏
- amazon-web-services - Ansbile + AWS 私有主机配置
- javascript - 为什么“从'datatables.net'导入数据表”可以在某些机器上工作,而在其他机器上不行?
- python - 无法使用 plt.plot() 从散点图中删除连接线
- javascript - 从 json 访问对象
- java - 使用Java中的数组计算字母频率
- reactjs - 每次我调用 OnDayPress 时,react-native-calendar 都会重新呈现到当前月份