Angular 将数据从子组件传递到父组件4
我有存储在服务器:ServerGetData中的API列表,如下所示:Angular 将数据从子组件传递到父组件4,angular,components,Angular,Components,我有存储在服务器:ServerGetData中的API列表,如下所示: apis = { "Repo Assignment": "https://apis.repoAssignment", "Status Summary": "https://apis.statsSummary", ... } 我已经创建了一个子组件下拉菜单:TitleDropdownComponent子组件,它显示所有api标题:“Repo分配”。。。在父组件中,我希望根据从子组件中选择的标题呈现不同的数据表 现在,我
apis = {
"Repo Assignment": "https://apis.repoAssignment",
"Status Summary": "https://apis.statsSummary",
...
}
我已经创建了一个子组件下拉菜单:TitleDropdownComponent子组件,它显示所有api标题:“Repo分配”。。。在父组件中,我希望根据从子组件中选择的标题呈现不同的数据表
现在,我可以成功地从子组件获取标题,并在父组件的控制台中打印它们,但是,在我的ngOnInit()中,相同的变量不能相应地更改,始终获取相同的api数据,因为标题变量没有更改。
如何在ngOnInit中更改title变量或使用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;
}
);
};
}
组件初始化时,
ngonit
始终只执行一次。当进行其他选择时,它不会在以后重新执行
如果每次选择新项时都需要重新设置数据,请将代码移动到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;
}
嗨@DeborahK,非常感谢!它起作用了。但是,我发现数据不能被覆盖,这意味着我得到的数据来自ngOninit和onSelected。无论如何,我只需要OnInIt运行一次,然后数据源将来自onSelected()?谢谢!我想我明白了。我刚刚更改了ngOnInit()下面onSelected()的顺序。