将数据从子组件传递到父组件Angular4

时间:2017-09-06 20:15:44

标签: angular components

我有存储在服务器中的api列表:ServerGetData,如下所示:

apis = {
 "Repo Assignment": "https://apis.repoAssignment",
 "Status Summary": "https://apis.statsSummary",
 ...
}

我创建了一个子组件下拉菜单:TitleDropdownComponent子组件,它显示所有api标题:“Repo Assignment”...在我的父组件中,我想根据从中选择的标题呈现不同的数据表子组件。

现在,我可以成功从子组件中获取标题并在父组件的控制台中打印它们。但是,在我的ngOnInit()中,相同的变量无法相应更改,因为标题变量总是得到相同的api数据不会改变。 如何在ngOnInit中更改标题变量或使用ngOnChanges等其他方式?请参阅下面的我的父应用组件。先谢谢!

import { Component, Input, EventEmitter, Output, ViewChild, OnInit } from '@angular/core';
import { ServerGetData } from './server.getData';
import { TitleDropdownComponent } from './TitleDropdown/titleDropdown.component'


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  // make ajax call from ServerGetData

  constructor(private dataService: ServerGetData) {}

  data = {};

  // get Child component variables

  @ViewChild(TitleDropdownComponent)
  private titleComponent: TitleDropdownComponent;

  onSelected(selected: string) {
    // default child component title is "Repo Assignment", in here overwrite 
    // titleComponent.title to be selected title
    this.titleComponent.title = selected;
    // each time can the selected title can be printed in console
    console.log(this.titleComponent.title);
    return this.titleComponent.title;
  }

  ngOnInit(): void {

   // *** No idea why in here this.titleComponent.title is not able to change accordingly and always is default title: "Repo Assignment" ***

    this.dataService.getData(this.titleComponent.title).subscribe(
      (data) => {
        this.data = data.items;
      }
    );
  };

}

1 个答案:

答案 0 :(得分:2)

ngOnInit只在组件初始化时始终执行一次。它不会在以后重新执行,因为其他选择。

如果您需要在每次选择新项目时重新获取数据,请将代码移至onSelected方法中。

  onSelected(selected: string) {
    // default child component title is "Repo Assignment", in here overwrite 
    // titleComponent.title to be selected title
    this.titleComponent.title = selected;
    // each time can the selected title can be printed in console
    console.log(this.titleComponent.title);

    this.dataService.getData(this.titleComponent.title).subscribe(
      (data) => {
        this.data = data.items;
      }
    );

    return this.titleComponent.title;
  }