【问题标题】:Data showing as undefined when I am trying to pass data from parent component to child components当我尝试将数据从父组件传递到子组件时,数据显示为未定义
【发布时间】:2018-12-13 12:10:53
【问题描述】:

我正在尝试将数据从父组件传递到子组件,但我得到的数据是undefined, 在我下面的代码中

父组件

这里 part_data 我已经在服务中声明了

this._PartService.GetDataValues(this.search.item, this.search.filter_type, release_part).subscribe(
  result => {
    this.resultData = result;
    this._PartService.part_data = this.resultData.data
  })

子组件

这里我用的是观察者

this.searchService.observer.subscribe(search => {
  this.part = search.item;
  this.specification = this._PartService.part_data.partMasterDataCompleteList[0];
})

我收到PartMasterDataCompleteList[0] is undefined

【问题讨论】:

  • 你是如何发送数据的?你在用@input吗?
  • 在访问值之前使用 If
  • 嗨,感谢您的回复,我没有使用@input,我只是通过属性发送数据,就我而言,我正在发送 part_data..
  • 我实际上想使用@input,所以请告诉我如何在我的情况下使用它
  • 您可以发布您的@Component({...}) 代码吗?

标签: html angular typescript angular5


【解决方案1】:

使用它作为子组件:-

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
  @Input() hero: Hero;

  constructor() {}

  ngOnInit() {}

}

当您需要向组件提供数据时,请使用以下代码:-

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

hero 属性是@Input,它接收来自外部环境的数据。

更多信息请参考Angular教程:-

https://angular.io/tutorial/toh-pt3

【讨论】:

  • 您能否更新完整代码或创建一个 StackBlitz 以便我们为您提供帮助?
  • 请检查stackblitz.com/edit/angular-6yjmr3.... Header.component 是我的父组件,part-detail 是我的子组件
  • 请把代码置于运行状态。以这种方式推断代码非常困难。谢谢
  • 我遇到了错误,所以很难进入运行状态。通过看到这两个组件,你能告诉我如何使用@Input...谢谢
  • 您是从父组件传递数据还是使用服务获取数据。我分享的链接信息量很大,请通过相同的链接。理解起来会很有帮助。
【解决方案2】:

您可以在子组件中传递您的数据并使用@Input 方法获取。

还有另一种方法可以将数据从一个组件传递到另一个组件。

Click here

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 2017-04-20
    • 2021-03-03
    • 2020-10-22
    • 2017-06-10
    • 2018-02-15
    • 2016-10-13
    相关资源
    最近更新 更多