Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 通过服务调用设置应用父字符串变量后,该变量将返回为空_Angular_Typescript_Angular2 Routing_Angular2 Services - Fatal编程技术网

Angular 通过服务调用设置应用父字符串变量后,该变量将返回为空

Angular 通过服务调用设置应用父字符串变量后,该变量将返回为空,angular,typescript,angular2-routing,angular2-services,Angular,Typescript,Angular2 Routing,Angular2 Services,我有两个具有父/子关系的应用程序组件。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) pub

我有两个具有父/子关系的应用程序组件。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
返回为空字符串,我不知道为什么。有什么想法吗?

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

我建议使用父组件和客户端组件之间的输入关系。请在此处阅读更多信息: