【问题标题】:App parent string variable is going back to being empty after being set by service call应用程序父字符串变量在服务调用设置后恢复为空
【发布时间】: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 又变成了一个空字符串,我不知道为什么。有什么想法吗?

【问题讨论】:

标签: angular typescript angular2-routing angular2-services


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多