有什么办法可以将动态数据传递给Angular中的组件吗?(Is there any way I can pass dynamic data to a component in Angular?)

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

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。 如何将动态数据传递给组件?

I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

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 }

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

最满意答案

问题是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。 容器将允许现在呈现子组件,这将保证在子组件将经历其生命周期时结果不为空。

The problem is that the UI thread will render the child component before the subscribe from the observable finished.

you need to do it like this:

import { ChangeDetectorRef } from '@angular/core'; constructor(private ref: ChangeDetectorRef) {} ngOnInit() { this.http.get('url').subscribe(data => { this.results = data; this.ref.markForCheck(); }); }

and in the HTML you have to test the value first.

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

A little description, the .markForCheck() will refresh the result after the subscribe and will inform all the components which are using this "value" to update its value, including the ng-container. The container would allow rendering the child component now, which will guarantee that the results are not null when the child will be going through its life cycle.

更多推荐