有什么办法可以将动态数据传递给Angular中的组件吗?

时间:2017-12-07 12:16:43

标签: angular typescript

我试图将动态数据传递给子组件。但我总是在子组件中获取未定义的数据。以下是我正在做的事情。

ParentComponent.ts

results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}

ParentComponent.html

<app-childComponent [dataNeeded]=results></app-childComponent>

ChildComponent.ts

@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}

正如预期的那样,它不会等待异步调用并返回undefined。如何将动态数据传递给组件?

4 个答案:

答案 0 :(得分:3)

问题是UI线程将在可观察完成的订阅之前呈现子组件。

你需要这样做:

import { ChangeDetectorRef } from '@angular/core';

constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
   this.http.get('url').subscribe(data => { 
     this.results = data;
     this.ref.markForCheck();
   });
}

在HTML中,您必须先测试该值。

<ng-container *ngIf="results != null">
    <app-childComponent [dataNeeded]=results></app-childComponent>
</ng-container>

稍微说明一下,.markForCheck()将在订阅后刷新结果,并将通知所有使用此“值”的组件更新其值,包括ng-container。容器现在允许渲染子组件,这将保证当子进行其生命周期时结果不为null。

答案 1 :(得分:2)

您可以尝试OnChanges生命周期钩子方法。

在您的情况下,您需要将其添加到子组件中,如下所示:

ngOnChanges(changes) {
  if (changes['dataNeeded'] && this.dataNeeded) {
    console.log(this.dataNeeded);
  }
}

PS 我刚刚注意到ChildComponent.ts中的语法错误,但缺少this

ngOnInit() {
 console.log(this.dataNeeded);
}

答案 2 :(得分:0)

如果您确定您的服务成功获得data,那么这将有效:

在父组件的html中添加引号:

<app-childComponent [dataNeeded]="results"></app-childComponent>

在您的子组件中,您将使用OnCh:

检查Input的更改
ngOnChanges(changes: SimpleChanges) {   
   for (let propName in changes) {
      // when your @Input value is changed  
      if(propName === "dataNeeded"){
          console.log(dataNeeded);
      }
   }
}

希望这会有所帮助:)

答案 3 :(得分:0)

为什么不将Observable与异步管道一起使用。 如果要控制台记录该值,请使用setter。 异步管道也会关注取消订阅。

results: Observable<any[]>;
ngOnInit() {
  this.results = this.http.get('url');
}

在HTML

<app-childComponent [dataNeeded]="results | async"></app-childComponent>

在你的孩子组件中

@Input('dataNeeded') 
set dataNeeded(val: any[]) {
  console.log(val);
}