【发布时间】:2017-04-20 00:52:49
【问题描述】:
我有两个具有父/子关系的应用组件。 AppComponent 是父级,而 ConfigComponent 是子级。当我启动我的应用程序时,AppComponent 在其构造函数中进行服务调用以设置变量,例如
// I've simplified my code to illustrate my issue. I've done all the proper
// service imports, providers, etc.
// AppComponent (the parent)
public configName: string = "";
constructor(//params here) {
console.log("App constructor called.");
this.getConfigName();
// Since I've already called the service method to obtain the config name,
// I expect the following line to print out the config name that was retrievevd, but instead it prints out nothing i.e. an empty string
console.log("Config name is: " + this.configName);
}
getConfigName() {
this.configService.getGATRConfigName()
.subscribe(res => this.configName = res;
console.log("Config name is: " + this.configName); // This prints out the proper name
);
}
// ConfigComponent (the child)
public configName: string = "";
constructor(private appParent: AppComponent) {
this.configName = this.appParent.configName;
// After this line is executed, this.configName is still an
// empty string - if I can figure out why the parent component
// doesn't seem to set the variable properly then I imagine
// this would work the way I want it to.
}
我还注意到,如果我在 AppComponent 父级中手动设置 configName,例如:
this.configName = "Config Name Default";
然后它会保留下来,我可以从子组件中提取该变量并取回“配置名称默认值”。出于某种原因,this.configName 又变成了一个空字符串,我不知道为什么。有什么想法吗?
【问题讨论】:
-
我建议在父组件和客户端组件之间使用输入关系。在这里阅读更多:sitepoint.com/angular-2-components-inputs-outputs
标签: angular typescript angular2-routing angular2-services