应用程序父字符串变量在由服务调用

时间:2017-04-19 16:28:40

标签: angular typescript angular2-routing angular2-services

我有两个具有父/子关系的app组件。 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";

然后它停留,我可以从子组件中提取该变量并返回“Config Name Default”。出于某种原因,this.configName又回到了一个空字符串,我不知道为什么。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的配置值不会返回空,getGATRConfigName实际上没有触发订阅正在侦听的事件。您需要设置一些您在订阅中解决的承诺,然后其他内容可以参考,以便知道您何时实际完成加载。