首页 文章

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

提问于
浏览
1

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

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

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

现在,我可以成功从子组件中获取 Headers 并在父组件的控制台中打印它们 . 但是,在我的ngOnInit()中,相同的变量无法相应地更改,因为 Headers 变量不会改变,所以总是得到相同的api数据 . 如何在ngOnInit中更改 Headers 变量或使用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 回答

  • 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;
      }
    

相关问题