javascript - 为什么我的输入变量属性未定义( Angular )

标签 javascript angular typescript input service

我在应用程序组件中从我的服务中获取数据,然后通过@Input 将其传递给子组件。当我 console.log ngOnInit 中的数据时,它确实显示在子组件中,但是当我尝试将它传递给变量并在子模板中使用它时,它返回未定义,我不确定为什么。

这是我在 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);
  }

}

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

最佳答案

所有 Observables 都是异步的,所以在模板 *ngIf 条件下将检查变量,如果它是 null 将返回 null 但如果您将变量作为 | async 它会一直检查这个变量,当变量不为空时它会显示内容 ngIf

*ngIf 只工作一次!!!他没有等待任何 http 调用,Observables 正在做一个 usualy。如果你想 *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。

关于javascript - 为什么我的输入变量属性未定义( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188384/

相关文章:

angular - 如何在 Angular 2 final 中扩展 Angular 2 http 类

html - 如何在 mat-table angular 7 中突出显示新插入的行

angular - TypeScript const 声明变量

javascript - 如何按特定键在数组中按字母顺序对对象进行分组?

javascript - 如何通过 jQueryUI AJAX 加载 AngularJS 内容?

javascript - 为什么我的 for 循环似乎只运行一次?

Angular Testing : provide injected @Attribute in TestBed

angular - 如何在 Spring Boot Jar 中集成 Angular 7 应用程序?

使用 Jquery 装饰的 Javascript 表单验证

javascript - 网站上自动/预定 JavaScript