加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:29:36 所属栏目:安全 来源:网络整理
导读:我试图将动态数据传递给子组件.但我总是在子组件中获取未定义的数据.以下是我正在做的事情. ParentComponent.ts results: any[];ngOnInit() {this.http.get('url').subscribe(data = this.results = data);} ParentComponent.html app-childComponent [dataN
我试图将动态数据传递给子组件.但我总是在子组件中获取未定义的数据.以下是我正在做的事情.

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

解决方法

问题是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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读