Tips for sending data returned asynchronously from an Observable in Angular from a Child component to its Parent

I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values) within the ngAfterViewInit() method in the parent component's HTML page load, it returns an empty value. However, upon clicking the apply button in the child component, an event is emitted and the console.log(this.values); inside the getValues($event) method successfully prints the values.

Below is my parent component .ts file:

name = 'ViewUI';
@ViewChild('ChildValues', { static: false }) childReference: ChildComponent;

 ngAfterViewInit() {
  this.values = this.childReference.this.responseValues;
  console.log(this.values);
  mapResponse(this.values);
}

In this case, `mapResponse(this.values)` method runs before the data is retrieved from `this.values` in the child component.
getValues($event) {
  this.values = $event;
  console.log(this.values);
  this.apply();
}

This is my parent component .html file:

<app-child #ChildValues (getEvent)=" getValues($event)" [name]="name"></app-child>

Here is my child component .html file:

<button (click)="applyResponses()" mat-raised-button>
  Apply
</button>

And lastly, here is my Child component .ts file:

  export class ChildComponent implements OnInit {
      responseValues = {
            names: [], ages: []
        };
      @Output() getEvent = new EventEmitter < any > ();
      @Input() name: string;
    
      ngOnInit() {
        this.getNames();
        this.getAges();
        console.log(this.name);
      }
    
     getNames() {
       this.apiService.getnames(Id).subscribe((names) => {
         this.responseValues.names = [names[0].name];
        });
     }
    
     getAges() {
       this.apiService.getages(Id).subscribe((ages) => {
         this.responseValues.ages = [ages[0].age];
        });
     }
      applyResponses() {
        this.getEvent.emit(this.responseValues);
        console.log(this.responseValues);
      }
    }

Any ideas on how to retrieve data from the child to the parent component during the parent page load?

Answer №1

Instead of defining a new emitter in the ngOnInit of the child component, why not try creating one there?

@Output()dataReceived= new EventEmitter < any > ();

ngOnInit()
{
   forkJoin(this.getNames(),this.getAges()).subscribe(([names,ages]:[any[],any[]])=>{
       this.dataReceived.emit({names:names,ages:ages})
   })
}

How about handling the emitted data in your parent component like so:

<app-child (dataReceived)="storeData($event)"></app-child>
storeData(data:any)
{
    console.log(data.names,data.ages)
}

Note: This is a response to a question from a comment. It's important to acknowledge that the data may not always be received immediately. To simulate a delay in server response, import 'delay' from 'rxjs/operators'

import {delay} from 'rxjs/operators'

Update the subscription to include a delay of 10 seconds:

this.apiService.getages(Id).pipe(
  delay(10000))
  .subscribe((ages) => {
     this.responseValues.ages = [ages[0].age];
    });

If you click the button before 10 seconds, the data may not be available yet.

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

An error occurred in Angular 4 where an expression was changed after it had been checked, causing a

Encountering an error and struggling to debug from the console: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Main Bike Trails'. at viewDebugE ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

Incorporate a visual element into an Angular Library Component Template using an image asset

Currently, I am working with Angular 10 and aiming to develop a component library that includes images and stylesheets. My main goal is to be able to access these images from the component templates defined in the HTML template. Although I have limited ex ...

Implementing a feature in Typescript/React component that provides autocomplete functionality

Currently, I have developed a TypeScript and React component that has been published on NPM. My goal is to enable IntelliSense to autocomplete React props for this component. While I typically use JSDoc for plain React components, it does not seem to work ...

Adjusting the transparency of the background image upon hovering in Angular with SCSS

I have an Angular component with a dynamic background image fetched from the server: <div class="picture" [style.background-image]="'url(' + this.category.photo + ')'" > <div class="seeDet ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

When running `ng serve` or `ng build --prod`, the dist folder is not created in an Angular 4 application

I recently completed building an Angular 4 app using angular-cli version 1.0.4 and generated the production build with the command ng build --prod. However, I encountered a problem as the expected dist folder was not created after executing this command. ...

Encountering challenges with Angular in creating a dynamically responsive background

I'm struggling to make this website fully responsive and adapt to various screen resolutions. The background images I'm using are high-resolution, but they don't seem to cover the entire page. CSS : @media screen and (max-width: 600px) { ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

I'm encountering an error while trying to build my Ag-Grid using npm run build, can someone help me figure out

Being relatively new to Next.js and web development in general, my background mainly consists of working with compiled languages. I recently embarked on a project to build a web app using Ag-Grid, drawing inspiration from an example I found on a public Git ...

Using React TypeScript to trigger a function upon route changes with react-router-dom

I am trying to use the useEffect hook to console log every time the location changes in my project. However, when I try to compile, I receive an error in the terminal saying Unexpected use of 'location' no-restricted-globals. I would like to fin ...

Can a lifecycle hook be interrupted in Angular 2?

Is there a way to prevent a Lifecycle Hook in angular2 from running when a specific variable becomes true? I have searched for information on this topic without success, but I believe it would be a great feature to have. ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

What causes an error during the compilation of an Angular package containing a singleton class?

I am currently in the process of creating an Angular library. Within this library, I have developed a singleton class to manage the same SignalR connection. Here is the code implementation: import * as signalR from '@microsoft/signalr'; export c ...

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

Invoking a functionality within a stream of events through an observable's subscribe

Service2.ts public flags$: BehaviorSubject<FlagName> = new BehaviorSubject<FlagName>("custom-flag-1"); This flag is set up as follows: private _setFlags = () => { const flagsData = this._customClient.getFlags(); if (f ...

Issue: No property named 'counterUp' has been defined on the 'JQLite' type

I’m attempting to implement the counterUp() function from JQuery into my Angular project, but I keep encountering an error. The error message mentions jqlite instead of jquery. I have attempted to rectify the issue but have not been able to find a su ...

Can I modify the cookie domain for NestJS SessionModule on a per-request basis?

I am currently using NestJS with SessionModule to handle user cookies successfully. However, I have a requirement to override the domain name for certain requests. I am uncertain about how to achieve this within NestJS, as the domain setting appears to b ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...