首页 > 解决方案 > 为什么我的输入变量属性未定义(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);
  }

}

我知道我可能遗漏了一些关于生命周期的简单内容。有人可以在这里指出我正确的方向吗?

标签: javascriptangulartypescriptinputservice

解决方案


所有 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。


推荐阅读