【问题标题】:How to pass data received from dataService in parent to child in Angular2如何在Angular2中将从父级的dataService接收到的数据传递给子级
【发布时间】:2018-01-22 00:33:54
【问题描述】:

我有一个父组件 app-parentapp-child。 在 app-parent 我变成了来自我的 DataService 的数据

@Component({
  selector: 'app-parent',
  providers: [DataService]
})

export class Part1Component implements OnInit {
  public title: string;

  constructor(public dataService: DataService) {}

  ngOnInit() {
    this.dataService.get().subscribe(data => {
      this.itemsSource = this.dataService.convert(data, 1);
      this.title = this.itemsSource[0];
          });
   return this.title;
  }

模板

 <div id="content">Hallo!</div>
    <app-child [title]='title'></app-child>

我想将标题传递给子组件。 所以在我的子组件中是:

@Injectable()
  export class InfoComponent implements OnInit, OnDestroy {
  @Input() title: any;

  ngOnInit() {
    console.log('Show me title')
    console.log(this.title);
}

所以,我尝试使用@Input() 来传递我的数据,但它不起作用(如果标题我变成未定义的)。我想,这是因为在我的父组件中,我首先成为 DataService 的数据(因为如果我在 app-parent 中将标题设置为一开始的值,例如

  public title = 'Hola!';

它有效..)

您能告诉我如何解决这个问题吗?

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    您的数据是异步获取的,所以当子组件OnInit 被触发时,title 还没有值。通过OnChanges,我们可以观察@Input的变化,所以你可以做的是:

    ngOnChanges() {
      console.log('Show me title')
      console.log(this.title);
    }
    

    只要输入 title 发生变化就会触发。如果你需要对title 做一些事情,你最好设置一个if 语句来检查它是否有价值,然后再尝试使用它,因为在第一次执行ngOnChanges 时,title 将是undefined.

    作为旁注,我不知道您要对父级中的return title 做什么,但这不会返回从subscribe 内部获得的值的任何内容。另外,为什么您的子组件标记为Injectable?这与您的问题无关,但想指出这一点。

    【讨论】:

      【解决方案2】:

      当你导航到子视图时

       import { NavController,........} from 'ionic-angular';
       .
       .
       this.dataService.get().subscribe(data => {
        this.itemsSource = this.dataService.convert(data, 1);
        this.title = this.itemsSource[0];
        this.navCtrl.push(ChildPage, { title: this.title })
       });
       .
       .
      

      当你进入子视图时

       import { NavParams,............} from 'ionic-angular';
       .
       .
       this.title = navParams.get('title')
       .
       .
      

      【讨论】:

        猜你喜欢
        • 2017-08-03
        • 2017-11-07
        • 1970-01-01
        • 2021-06-29
        • 2018-03-09
        • 2023-03-13
        • 1970-01-01
        • 2020-09-22
        相关资源
        最近更新 更多