为什么我的输入变量属性未定义(角度)

时间:2019-10-01 15:49:58

标签: javascript angular typescript input service

我正在从应用程序组件中的服务中获取数据,然后通过@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);
  }

}

我知道我可能在生命周期方面缺少一些简单的东西。有人可以在这里指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

所有Observable都是异步的,因此在模板*ngIf中,条件将检查变量,如果为null,则返回null,但是如果您将变量传递为| async,它将一直在检查该变量,何时将变量apear not 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>

“管道异步”将为您订阅可观察对象。