我的@Input()在My Angular 2应用程序中没有传递信息

时间:2017-02-03 21:19:00

标签: javascript angular parent-child

在我的Angular2应用程序中,我有一个子组件,我在其中使用@Input()从父组件传递信息。在我的父组件视图/ HTML中,我绑定到子组件选择器并从我的父组件传入信息。父组件视图代码如下所示:

<div class="page-view">
    <div class="page-view-left">
        <admin-left-panel></admin-left-panel>
    </div>
    <div class="page-view-right">
        <div class="page-content">
            <admin-tabs></admin-tabs>
            <table-display [APICall]="accountCall"></table-display>
        </div>
    </div>
</div>

然后,对于组件文件,我有这个相关的代码,显示在我的ngOnInit中调用的服务函数。我将其保存在变量“accountCall”中。这就是我在子组件选择器“table-display [APICall] =”accountCall“中的上述视图中绑定的值:

ngOnInit() {
    this.accountCall = this.localAccountService.getByStage()
        .subscribe(resRecordsData => this.records = resRecordsData,
        responseRecordsError => this.errorMsg = responseRecordsError);
}

然后,在名为“table-display”的子组件中,我使用@Input()传递“APICall” - (即它知道它)。这是相关的组件代码:

@Component({
  selector: 'table-display',
  templateUrl: './table-display.component.html',
  styleUrls: ['./table-display.component.less']
})
export class TableDisplayComponent implements OnInit {

    @Input() APICall;

无论出于何种原因,这都行不通。我没有收到错误。我只是没有填充任何数据到页面。

另外,仅供参考,当我直接传递服务电话时,这确实有效。当我使用@Input()将信息从父级传递给子级时,它就无法工作。

修改 有几个人建议我只绑定到“记录”,并使@Input()传递给子组件,因为它包含了observable的结果,而不仅仅是observable本身。这是一个好主意。我尝试实现这个,但我现在得到了未定义的错误 - 而当我直接从子组件调用服务时,我没有。不知道为什么会这样。

2 个答案:

答案 0 :(得分:0)

而不是传递

<table-display [APICall]="accountCall"></table-display>

为什么不传递呼叫产生的数据?

<table-display *ngIf="records" [asyncRecords]="records"></table-display>

请注意,accountCall是Observable,而不是调用的结果。

编辑:

根据您的更新,其他父组件仍然可以使用此组件并使用他们拥有的任何记录...

<table-display *ngIf="records" [asyncRecords]="records"></table-display>
<table-display *ngIf="records" [asyncRecords]="data"></table-display>
<table-display *ngIf="records" [asyncRecords]="tableStuff"></table-display>

如果记录形状不同,您可以随时传递其他内容以通知孩子格式:

<table-display *ngIf="records" [asyncRecords]="records" [displayType]="mainRecordType"></table-display>

答案 1 :(得分:0)

尝试将“记录”传递给“accountCall”