The string variable in the parent app is resetting to empty after being populated by the service call

I am facing an issue with my app components where AppComponent acts as the parent and ConfigComponent as the child. In the constructor of AppComponent, a service call is made to set a variable but I encounter unexpected behavior when trying to access this variable in ConfigComponent.

// Simplified code snippet showcasing the problem 
// Proper service imports and providers have been implemented

// AppComponent (the parent)
public configName: string = "";

constructor(//params here) {
    console.log("App constructor called.");

    this.getConfigName();

    // Despite calling the service method to obtain the config name,
    // the following line prints out an empty string instead of the retrieved name
    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 execution of this line, configName remains empty
    // If the parent component sets the variable correctly, this would work as intended
}

Upon manually setting configName in AppComponent:

this.configName = "Config Name Default";

The value stays and can be fetched from the child component as expected. However, the issue arises when this.configName reverts back to being empty unexpectedly. Any insights on why this might be happening?

Answer №1

The value of your configuration is not resetting to empty because the getGATRConfigName function has not yet triggered the event that the subscribe method is listening for. To address this, you will need to implement a promise mechanism that resolves within your subscribe function. This will allow other parts of your code to reference it and determine when the loading process has been completed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript's Accessor decorator ensures that the decorated code is executed only once, fetching the previously calculated value for any subsequent calls

The topic discussed here originates from a previous discussion on a method decorator in Typescript. In some scenarios, there are `get` methods in a Typescript class that involve intensive computations. Some of these methods always return the same result an ...

The combination of Angular's *ngIf directive and ng-template is causing issues

When I have up to 3 icons, I require less space compared to when I have 3 icons or more. To address this issue, I have implemented the following code that utilizes both *ngIf and ng-template. Unfortunately, the implementation is not functioning as expect ...

When employing GraphQL Apollo refetch with React, the update will extend to various other components as well

My current setup involves using react along with Apollo. I have implemented refetch in the ProgressBar component, which updates every 3 seconds. Interestingly, another component named MemoBox also utilizes refetch to update the screen at the same int ...

Showcasing an Angular Material Dialog following a delay of x seconds

I'm currently working on integrating an Angular Material Dialog and I would like it to appear x seconds after the user clicks the openDialog button. Is this achievable? ...

Guide on developing a custom object type, with keys that are derived from the values in the original object

I'm attempting to transform an object into a dynamically created type, but I'm having difficulty getting it to work correctly. Imagine I have the following object: const constants = { filter: 'flr', color: 'col' } Is ...

Verification of German Numbers

Is there a way to validate a textbox for input in German number format? I searched through the Validators documentation, but I couldn't find any specific validators for numbers. Examples of German number formats: 0 12,5 100.000 100.000,25 ...

Creating an Angular 7 Template using HTML CSS and Javascript

I recently acquired a template that comes with HTML, CSS, and Javascript files for a static webpage. My goal is to integrate these existing files into my Angular project so I can link it with a Nodejs application to create a full-stack webpage with backend ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

Error: setPosition function only accepts values of type LatLng or LatLngLiteral. The property 'lat' must be a numerical value in agm-core agm-overlay

Currently, I am utilizing Angular Maps powered by Google @agm-core and agm-overlay to implement custom markers. However, when using the (boundsChange) function on the agm-map component, an error occurs with the message "invalidValueError: setPosition: not ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...

Typescript (ionic) loading animation that keeps users engaged while waiting for the data to be loaded

I'm looking to include an animation on the screen while waiting for the projects to load. constructor( public platform: Platform, private network: NetworkService, public navContrl: NavController, public modalCtrl: Moda ...

Managing events like onClick for custom components in Next.js and React: A Beginner's Guide

Utilizing tailwindCSS for styling and writing code in Typescript with Next.JS. A reusable "Button" component has been created to be used across the platform. When the button is pressed, I aim to update its UI in a specific way. For instance, if there&apos ...

Incorporating a new attribute into the JQueryStatic interface

I am trying to enhance the JQueryStatic interface by adding a new property called someString, which I intend to access using $.someString. Within my index.ts file, I have defined the following code: interface JQueryStatic { someString: string; } $.s ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

The angular-oauth2-oidc library is having issues loading the jsrsasign module

I'm currently working on upgrading a dependency in Angular for a project that was forked from: https://github.com/mgechev/angular-seed The dependency in question is located at: https://github.com/manfredsteyer/angular-oauth2-oidc. However, I'm f ...

Issue: npm encountered an error due to writing after reaching the end

I've encountered a problem while trying to install Cordova and Ionic. Due to what appears to be a corrupted installation, I had to uninstall NodeJS - Cordova - Ionic. After re-installing NodeJS successfully, the trouble began when running the pop ...

What are the steps for integrating Angular Material into an existing project?

I have recently set up an Angular 2 project. Attempting to integrate Angular Material into my existing project, I followed the steps outlined in the official documentation by running the npm command: npm install --save @angular/material @angular/cdk How ...

Angular Error: Property 'map' is not found in type 'OperatorFunction'

Code: Using map and switchMap from 'rxjs/operators'. import { map, switchMap } from 'rxjs/operators'; Here is the canActivate code for route guard: canActivate(): Observable<boolean> { return this.auth.userObservable ...

Leveraging the @Input Decorator in Angular 2

Check out the Angular 2 component code sample below @Component({ selector: 'author-edit', templateUrl:'./author/edit' }) export class AuthorEditComponent implements OnInit{ @Input() author: AuthorModel; fg: FormGroup; c ...

Sorting with lodash in Angular 2

Section: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import * as _ from 'lodash'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table ...